Yii CDbCommand create query

前端 未结 1 1966
-上瘾入骨i
-上瘾入骨i 2020-12-22 09:17

I can\'t create the following query using Yii:

SELECT recipientId as broadcasterId, SUM(quantity) as quantity FROM `creditlog` 
WHERE websiteId=3 AND timeAdd         


        
相关标签:
1条回答
  • 2020-12-22 09:49

    Since you don't have access to andWhere, which would make life much simpler, you have to express the parameters with where like this:

    $command->where(array(
        array('and', 
              'websiteId=:websiteId',
              array('and', 
                    'timeAdded>=:dateStart',
                     array('and',
                           // ...
    
    ), $parameters);
    

    This is done so that you can at some point use the proper array('in', 'recipientId', $values) syntax to produce the IN(...) SQL.

    However, this is ugly and difficult to manage. As long as all the conditions are simply joined together with AND you can construct the data structure programmatically from a saner data representation like this (in effect this is a workaround for the missing andWhere):

    $conditions = array(
        'websiteId=:websiteId',
        'timeAdded>=:dateStart',
        'timeAdded<=:dateEnd',
        array('in', 'recipientId', $broadcasterIds),
    
    );
    
    $where = null;
    foreach ($conditions as $condition) {
        if (!$where) {
            $where = $condition;
        }
        else {
            $where = array('and', $where, $condition);
        }
    }
    
    $command->where($where, $parameters);
    

    For more information on why this way of expressing things has to be used you can refer to the documentation for CDbCommand::where.

    0 讨论(0)
提交回复
热议问题