如何将mysql查询转换为Yii CDbCriteria对象?

时间:2012-11-02 08:39:17

标签: yii

我有一个模型Reporter

public function relations() {
    return array(
        'video' => array(self::HAS_MANY, 'Video', 'reporter_id'),
    );
}

我有Reporter->search()方法的mysql查询:

SELECT t.*, COUNT(t1.id) AS 'reports'
FROM reporter AS t
LEFT JOIN video AS t1 ON t.id = t1.reporter_id  
GROUP BY t.id
ORDER BY t.name

如何使用CDbCriteriaCActiveDataProvider一起编写?

1 个答案:

答案 0 :(得分:0)

要将该查询写入CActiveDataProvider的条件,您需要从CDbCriteria设置以下属性:

selectjoingroup,和 order

然后您可以在创建新的CActiveDataProvider对象时设置它们,如下所示:

$dataProvider=new CActiveDataProvider('Reporter', array(
    'criteria'=>array(
        'select'=>'`t`.*, count(`t1`.`id`) as `reports`',
        'join'=>'LEFT JOIN `video` AS `t1` ON `t`.`id` = `t1`.`reporter_id`',
        'group'=>'`t`.`id`',
        'order'=>'`t`.`name`',
    ),
));

可以在此处找到可与CDbCriteria一起使用的属性和方法的完整列表:CDbCriteria Class Reference