如何在Yii $条件中使用DATE_ADD?(How use DATE_ADD in Yii $criteria?)

Model.php

// Declare $datetime_limit public datetime_limit;

Controller.php这样

// datetime_limit should be the actual datetime + 5 days $criteria->select="DATE_ADD(NOW(), INTERVAL 5 DAY) AS datetime_limit";

错误信息:

Active record "Users" is trying to select an invalid column "DATE_ADD(NOW()". Note, the column must exist in the table or be an expression with alias.

编辑1:

我想使用关系表(多对多)过滤查找条件。 所以datetime_limit不能在关系events.datetime 。 我怎样才能做到这一点?

$criteria->select=array("DATE_ADD(NOW(), INTERVAL 5 DAY) AS datetime_limit"); $criteria->with=array('events'); $criteria->having='datetime_limit!=`events`.`datetime`'; $models=Users::model()->findAll($criteria);

Model.php

// Declare $datetime_limit public datetime_limit;

Controller.php

// datetime_limit should be the actual datetime + 5 days $criteria->select="DATE_ADD(NOW(), INTERVAL 5 DAY) AS datetime_limit";

Error Message:

Active record "Users" is trying to select an invalid column "DATE_ADD(NOW()". Note, the column must exist in the table or be an expression with alias.

Edit 1:

I would like to filter the find w/ a condition using a relation table (Many to Many). So the datetime_limit cannot have in relational events.datetime. How can I do that?

$criteria->select=array("DATE_ADD(NOW(), INTERVAL 5 DAY) AS datetime_limit"); $criteria->with=array('events'); $criteria->having='datetime_limit!=`events`.`datetime`'; $models=Users::model()->findAll($criteria);

最满意答案

CActiveFinder::getColumnSelect抛出此异常。

当CDbCriteria::$select是一个字符串时,它被视为逗号分隔列的简单列表。 您的表达式被解释为两个不同的列。 你可以通过自己设置select到一个数组来解决这个问题 - 在这种情况下,逗号分割没有完成1

$criteria = new CDbCriteria(); $criteria->select = array("DATE_ADD(NOW(), INTERVAL 5 DAY) AS datetime_limit"); $models = Users::model()->findAll($criteria);

请注意,如果您编写的别名与公共模型属性或数据库字段不对应,则会检索它但会被忽略 - 由于某种原因,Yii不会为此抛出异常。


1但是,此功能仍将尝试查找. 在表达式中并将其后面的部分解释为列标识符 - 不要使用. 在你的表达中,你应该没事。

This exception is thrown in CActiveFinder::getColumnSelect.

When CDbCriteria::$select is a string, it's treated as a simple list of comma-delimited columns. Your expression gets interpreted as two distinct columns. You can work around this by setting select to an array yourself - in this case the comma splitting is not done1:

$criteria = new CDbCriteria(); $criteria->select = array("DATE_ADD(NOW(), INTERVAL 5 DAY) AS datetime_limit"); $models = Users::model()->findAll($criteria);

Note that if you write an alias that doesn't correspond to a public model property or a DB field, it will be retrieved but silently ignored - for some reason Yii doesn't throw an exception for that.


1 However, this function will still attempt to find a . in the expression and interpret the part after it as a column identifier - don't use . in your expression and you should be fine.

更多推荐