问题描述
模型.php
// Declare $datetime_limit
public datetime_limit;
控制器.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:
Edit 1:
我想使用关系表(多对多)过滤带有条件的查找.所以 datetime_limit
在关系 events.datetime
中不能有.我该怎么做?
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
设置为数组来解决此问题 - 在这种情况下,逗号拆分未完成:
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 done:
$criteria = new CDbCriteria();
$criteria->select = array("DATE_ADD(NOW(), INTERVAL 5 DAY) AS datetime_limit");
$models = Users::model()->findAll($criteria);
请注意,如果您编写的别名与公共模型属性或数据库字段不对应,它将被检索但会被静默忽略 - 由于某种原因 Yii 不会为此抛出异常.
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.
但是,此函数仍会尝试在表达式中查找 .
并将其后的部分解释为列标识符 - 不要使用 .
在你的表达中,你应该没问题.
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.
这篇关于如何在 Yii $criteria 中使用 DATE_ADD?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!