如何在Yii中的criteria->条件中使用联合查询?

时间:2015-04-09 10:19:25

标签: php mysql yii

SELECT p_name
FROM projects
WHERE m_id =3
UNION SELECT p.p_name
FROM projects p, tasks t, users u
WHERE t.t_assignee =3
AND p.m_id =3
AND u.role !=1

这是我的查询,我想在我的模型中实现此查询。我在这个查询中使用了3个表。这是我的模型项目。在这里,我想根据上述查询列表。

public function search()
{
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.

    $criteria=new CDbCriteria;

    $criteria->compare('project_id',$this->project_id);
    $criteria->compare('p_name',$this->project_name,true);
    $criteria->compare('m_id',$this->manager_id);
    $criteria->compare('description',$this->description,true);


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



}

如何在此处实现此查询?

$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'projects-grid',
'dataProvider'=>$model->search(),
'ajaxUpdate' => false,
'filter'=>$model,
'columns'=>array(
array(
'name' => 'project_id',
'value'=>'$data["project_id"]', //in the case we want something custom
  ),
array(
'name' => 'project_name',
'value'=>'$data["project_name"]', //in the case we want something custom
),
array(
'name' => 'manager_id',
'value'=>'$data["manager_id"]', //in the case we want something custom
                    ),
array(
'name'=>'description',
'value'=>'strip_tags($data["description"])'
),  
array(
'class'=>'CButtonColumn',
'template'=>'{view} {update} {delete}{createtask}{viewtask}',
'buttons'=>array
(

),
),
),
));   

这是我的cgridview视图。试图获得非对象的属性仍然显示。

1 个答案:

答案 0 :(得分:0)

在这种情况下,使用CSqlDataProvider将比CActiveDataProvider更容易:

$sql = "
SELECT p_name
FROM projects
WHERE m_id =3
UNION SELECT p.p_name
FROM projects p, tasks t, users u
WHERE t.t_assignee = :t_assignee
AND p.m_id = :m_id
AND u.role != :role
";

return new CSqlDataProvider($sql, [
    'params' => [
        ':t_assignee' => 3,
        ':m_id' => $this->manager_id,
        ':role' => 1,
    ]
]);

您必须在'项目'中添加其他属性。模型能够按角色搜索'和' t_assignee'字段