首先,我使用以下代码:
$c = new CDbCriteria();
$c->select = '*, DATEDIFF(deadline_time, NOW()) AS day_left';
$c->addCondition('DATEDIFF(deadline_time, NOW()) > 0');
$c->addCondition('DATEDIFF(deadline_time, NOW()) < :diff');
$c->params += array(':diff' => $diff);
$assigns = UserAssign::model()->findAll($c);
查询工作正常,但我想通过关系添加一些新条件,所以代码变成这样:
$c = new CDbCriteria();
$c->with = array('user');
if(Yii::app()->user->model->isAreaAdministrator) {
$c->addCondition('user.city_id = :cityId');
$c->params += array(':cityId' => Yii::app()->user->model->adminCityId);
}
$c->select = '*, DATEDIFF(deadline_time, NOW()) AS day_left';
$c->addCondition('DATEDIFF(deadline_time, NOW()) > 0');
$c->addCondition('DATEDIFF(deadline_time, NOW()) < :diff');
$c->params += array(':diff' => $diff);
$assigns = UserAssign::model()->findAll($c);
添加with
属性后,查询似乎无效,它会转发消息trying
to select an invalid column "DATEDIFF(deadline_time"
错误。
我是Yii的新手,任何人都可以帮助我吗? 感谢。
答案 0 :(得分:2)
使用
替换条件中的DATEDIFF(deadline_time, NOW())
new CDbExpression('DATEDIFF(deadline_time, NOW())')
我不确定它是否适用于select
。如果不是,您可以使用afterFind
函数将公共变量$day_left
设置为DATEDIFF(deadline_time, NOW())'
class UserAssign{
public $day_left;//new variable
...
public function afterFind(){
$this->day_left=date_diff(date_create($this->deadline_time),date_create('now'))->format('%R%a days');
return parent::afterFind();
}
}