1

首先,我使用以下代码:

$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 的新手,有人可以帮助我吗?谢谢。

4

1 回答 1

2

DATEDIFF(deadline_time, NOW())在条件中替换为

new CDbExpression('DATEDIFF(deadline_time, NOW())')

我不确定它是否有效select。如果不是,您可以使用该afterFind函数将公共变量设置$day_leftDATEDIFF(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();
    }
}
于 2013-03-30T21:25:46.403 回答