如何在Yii $标准中使用DATE_ADD,特别是在select中?

时间:2014-04-08 07:08:12

标签: php yii

这个sql部分的代码是

$criteria = new CDbCriteria;
.......
$criteria->select = 'user.user_id as userId, user.name as userName, COUNT(*) AS totalCount,
                        SUM(CASE WHEN (t.create_datetime > (SELECT DATE_ADD(curdate(), INTERVAL(2-DAYOFWEEK(curdate())) DAY)) AND t.create_datetime < \'2013-06-08\') THEN 1 ELSE 0 END) AS weeklyCount,
                        SUM(CASE WHEN (MONTH(t.create_datetime) = 9 ) THEN 1 ELSE 0 END) AS monthlyCount';
.......
$criteria->group = 'user.user_id';
$criteria->with = array('user');
$criteria->addCondition('t.deleted=0', 'AND');
$criteria->addCondition('t.user_id = user.user_id', 'AND');

我得到的错误是:

Type: CDbException
Active record `Inspection` is trying to select an invalid column `SUM(CASE WHEN (t.create_datetime > (SELECT DATE_ADD(curdate()`. Note, the column must exist in the table or be an expression with alias.

我看了一下:How use DATE_ADD in Yii $criteria?这是Yii date_add$criteria的解决方案。但在我的情况下,日期添加不是选择,它是选择中的条件。

请帮帮我。感谢

1 个答案:

答案 0 :(得分:0)

创建一个select语句的数组,这样Yii可以&#34;识别&#34;别名(如果$criteria->select是一个字符串,它不知道在哪里寻找别名):

$criteria->select = array(
   'user.user_id AS userId', 
   'user.name AS userName', 
   'COUNT(*) AS totalCount',
   'SUM(CASE WHEN (t.create_datetime > (SELECT DATE_ADD(curdate(), INTERVAL(2-DAYOFWEEK(curdate())) DAY)) AND t.create_datetime < \'2013-06-08\') THEN 1 ELSE 0 END) AS weeklyCount',
   'SUM(CASE WHEN (MONTH(t.create_datetime) = 9 ) THEN 1 ELSE 0 END) AS monthlyCount'
);