在Yii中按CDbCriteria选择表达式

时间:2013-03-30 08:11:06

标签: mysql yii

首先,我使用以下代码:

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

1 个答案:

答案 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();
    }
}