子查询与Yii活动记录

时间:2015-11-10 03:18:48

标签: php activerecord yii

是否可以使用Yii活动记录编写子查询?

我需要在FROM子句中添加子查询。下面是带有子查询的SQL,但我想使用Active Record专门编写它。

在SQL中,Policy与policy_vehicles有很多关系。

SQL查询:

select * from (SELECT Name , GROUP_CONCAT(PV.VehicleId SEPARATOR ',') as VehicleIds 
FROM `policies` `t` 
LEFT JOIN policy_vehicles PV USING(PolicyId)
WHERE (Type IN ('C', 'E')) AND (Status='Active')
GROUP BY t.PolicyId 
) k where VehicleIds like '%1%' AND VehicleIds like '%2%'

这就是我想在Controller类中使用它的方法:

$model = Policy::model();
$model->Status = array('Active');
$model->VehicleIds = array(1,2);
$model->Type = array('C', 'E');
$datas = $model->search()->getData();
print_r($datas);

模型中的搜索功能:

public function search() {

    $joins = array();
    $criteria = new CDbCriteria;
    $criteria->compare('Type', $this->Type);
    $criteria->compare('Status', $this->Status);

    array_push($joins, 'LEFT JOIN policy_vehicles PV USING(PolicyId)');
    $criteria->join = implode(' ', $joins);

    return new CActiveDataProvider($this, array(
        'criteria' => $criteria,
    ));
}

0 个答案:

没有答案