0

我无法使用 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 条件,但我找不到重写它的方法。

4

1 回答 1

4

由于您无权访问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.

于 2013-01-17T10:35:57.140 回答