小编典典

Yii CDbCommand创建查询

sql

我无法使用Yii创建以下查询:

SELECT recipientId as broadcasterId, SUM(quantity) as quantity FROM `creditlog` 
WHERE websiteId=3 AND timeAdded>='2013-01-17' 
AND timeAdded<='2013-02-17' 
AND recipientId IN (10000024, 10000026, 1000028) GROUP BY `recipientId`

我试过了:

$command = Yii::app()->db->createCommand();
$command->select('recipientId as broadcasterId, SUM(quantity) as quantity');
$command->from('creditlog');

$command->where('websiteId=:websiteId AND timeAdded>=:dateStart AND timeAdded<=:dateEnd AND recipientId IN (:recipients)',array(':websiteId' => $websiteId, ':dateStart' => $dateStart, ':dateEnd' => $dateEnd, ':recipients' => $broadcasterIds));

$command->group('recipientId');

而且andWhere()文档中的功能似乎丢失了。

问题是IN条件,但是我找不到重写它的方法。


阅读 164

收藏
2021-03-17

共1个答案

小编典典

由于您无权访问andWhere,这会使工作变得更加简单,因此您必须where像这样表达参数:

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

), $parameters);

这样做是为了使您可以在某个时候使用正确的array('in', 'recipientId', $values)语法来生成IN(...)SQL。

然而,这是丑陋的并且难以管理。只要将所有条件简单地结合在一起,AND您就可以像这样更合理的数据表示形式以编程方式构造数据结构(实际上,这是缺少的变通方法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);

有关为何必须使用这种表达方式的更多信息,请参考的文档CDbCommand::where

2021-03-17