ColdFusion在基于脚本的cfc函数中使用if条件

问题描述 投票:3回答:3

我正试图在我的cfscript上变得更好,并且无法弄清楚这一点。在基于标签的CFC中,我可以这样做:

<cffunction name="querySd" access="public" returnType="query" output="false">
  <cfargument name="sd_id" type="numeric" required="No"/>
  <cfargument name="sd_code" type="string" required="No"/>
  <cfquery name="LOCAL.qrySd" datasource="#variables.dsn#">
    SELECT sd_id, sd_code, sd_active, sd_expires, sd_added, sd_dla
     FROM sd 
    WHERE 0=0
     <cfif isDefined("ARGUMENTS.sd_id")>
       AND sd_id = <cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#ARGUMENTS.sd_id#"/>
     </cfif>
     <cfif isDefined("ARGUMENTS.sd_code")>
      AND sd_code = <cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#ARGUMENTS.sd_code#" maxlength="20"/>
     </cfif>
    </cfquery>
  <cfreturn LOCAL.qrySd>
</cffunction>

但是,在cfscript中尝试类似的方法会引发错误:

public query function querySd( numeric sd_id, string sd_code ){
  local.querySd = new Query(datasource = variables.dsn);
  if( isDefined('arguments.sd_id') ){
    local.querySd.addParam( name = 'sdid', value = arguments.sd_id, cfsqltype = 'cf_sql_int');
  };
  if( isDefined('arguments.sd_code') ){
    local.querySd.addParam( name = 'sdcode', value = arguments.sd_code, cfsqltype = 'cf_sql_varchar', maxlength = '20');
  };

 local.querySd.setSql('
            SELECT sd_id, sd_code, sd_active, sd_expires, sd_added, sd_dla
              FROM sd
             WHERE 0 = 0
             if( isDefined('arguments.sd_id') ){
                 AND sd_id = :sdid 
             };
             if( isDefined('arguments.sd_code') ){
                 AND sd_code = :sdcode 
             };
        ');
local.qrySd = local.querySd.execute().getResult();

在cfc中基于cfscript的查询中使用可选参数的正确方法是什么?

coldfusion cfml
3个回答
3
投票

正如其他人所说,根据您使用的CF版本,我会使用queryExecute()而不是new Query()。原因有很多,而且这本身就是一个完整的其他主题。

无论如何,现在我有一分钟,我已经把queryExecute()的一个例子扔到了一起完整。注意:我在这里使用查询模拟数据的查询。真正的查询将使用实际的数据源。

<cfscript>
public Query function querySd2 ( Numeric sd_id, String sd_code ) {
    // This is my fake query data, thanks to Mockaroo.
    local.sd = queryNew("sd_id,sd_code,sd_active,sd_expires,sd_added,sd_dla",
    "integer,varchar,bit,date,date,varchar",
    [ 
        { "sd_id":1,"sd_code":"DontPickMe","sd_active":true,"sd_expires":"2019-01-04","sd_added":"2018-05-07","sd_dla":"2M66CAf3" } ,
        { "sd_id":2,"sd_code":"PickMe","sd_active":true,"sd_expires":"2018-03-03","sd_added":"2018-08-18","sd_dla":"8FW4HRm8" } ,
        { "sd_id":3,"sd_code":"DontPickMe","sd_active":true,"sd_expires":"2019-01-01","sd_added":"2018-10-28","sd_dla":"4F6kBUm2" } ,
        { "sd_id":4,"sd_code":"PickMe","sd_active":false,"sd_expires":"2018-10-28","sd_added":"2018-08-22","sd_dla":"2NSlNLr8" } ,
        { "sd_id":5,"sd_code":"DontPickMe","sd_active":false,"sd_expires":"2018-03-07","sd_added":"2019-02-09","sd_dla":"8T0cWQc2" }
    ]);
    ////////////////

    local.sqlWhere = "1=1" ; // This is our default WHERE condition.
    local.qryParams  = {} ;  // queryExecute expects a struct of params. Or an array.

    // First, I check that the given args have a length, then create both 
    // the SQL and the param. Also "?." is the safe-navigation operator, added
    // in CF2016. https://helpx.adobe.com/coldfusion/using/language-enhancements.html
    if( len(trim(arguments?.sd_id)) ) {
        sqlWHERE &= " AND sd_id = :sdid" ;  // This is our SQL string. 
        qryParams.sdid = { value:arguments.sd_id, cfsqltype:"cf_sql_integer" } ;
    }

    if( len(trim(arguments?.sd_code)) ) {
        sqlWHERE &= " AND sd_code = :sdcode" ;
        qryParams.sdcode = { value:arguments.sd_code, cfsqltype:"cf_sql_varchar", maxlength:"20" }  ;
    }

    //writeDump(sqlWhere) ;

    // https://cfdocs.org/queryexecute
    local.qrySd = queryExecute( 
          "SELECT sd_id, sd_code, sd_active, sd_expires, sd_added, sd_dla FROM sd WHERE #sqlWhere#" 
        , qryParams 
        , { dbtype="query"} //datasource="dsn" } // Replace dbtype with datasource.
    ) ;
    return qrySd ;  // return our query object.
}

// TESTS
tests = [
    {qry:querySd2(2,"PickMe")         , label:"Results from query"                 , retval:querySd2(2,"PickMe").sd_expires } ,
    {qry:querySd2(1,"PickMe")         , label:"No Results from query"              , retval:querySd2(1,"PickMe").sd_expires } ,
    {qry:querySd2(1)                  , label:"No Param2"                          , retval:querySd2(1).sd_expires } ,
    {qry:querySd2(sd_code = "PickMe") , label:"No Param1 (CF2018+ (named params))" , retval:querySd2(sd_code = "PickMe").sd_expires } ,
    {qry:querySd2()                   , label:"No Params"                          , retval:querySd2().sd_expires } ,
    {qry:querySd2(1," ")              , label:"Edge. Empty string."                , retval:querySd2(1," ").sd_expires } 
] ;
//// Note that the above retval:querySd2().sd_expires only outputs one row. Loop
//// through the results themselves to output the multiple rows. 

writeDump(tests) ;
</cfscript>

https://cffiddle.org/app/file?filepath=32c93137-adb1-4f58-8ed4-21bb9e5212b2/ee3d9cac-e25e-46ca-8eec-f4ac8ddd4b41/4d295400-65fa-4b76-a889-a97a805409ea.cfm

注意:在CF11中添加了queryExecute()。安全导航(?.)在CF2016中添加。

编辑:我将我的Mockaroo数据更改为静态查询数据。显然,你可以很快地浏览Mockaroo数据。 :-)


4
投票

您可以将查询的一部分放在变量中,并在查询字符串中使用它。

local.queryPart = '';
if( isDefined('arguments.sd_id') ){
    local.queryPart &= ' AND sd_id = :sdid ';
};
if( isDefined('arguments.sd_code') ){
    local.queryPart &= ' AND sd_code = :sdcode ';
};
local.querySd.setSql('
    SELECT sd_id, sd_code, sd_active, sd_expires, sd_added, sd_dla
    FROM sd
    WHERE 0 = 0
    #local.queryPart#
');

2
投票

您也可以使用三元运算符:

local.querySd.setSql('
        SELECT sd_id, sd_code, sd_active, sd_expires, sd_added, sd_dla
          FROM sd
         WHERE 0 = 0
         # !isNull( arguments.sd_id ) ? ' AND sd_id = :sdid' : '' #
         # !isNull( arguments.sd_code ) ? ' AND sd_code = :sdcode' : '' #
    ');

就个人而言,我发现这更具可读性。

© www.soinside.com 2019 - 2024. All rights reserved.