我无法使用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条件,但我无法找到重写它的方法。
答案 0 :(得分: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
的文档。