在yii2中编写连接查询

时间:2016-05-13 17:21:40

标签: mysql yii2 inner-join

我想用yii2格式编写连接查询。我们在joinWith函数中编写的查询将表与主表连接而不是连接中提到的内表

select table1.id,table1.name
from
table1
inner join
table2
on
table1.id=table2.id
inner join
table3
on
table2.id=table3.id

1 个答案:

答案 0 :(得分:0)

这里的示例简单方法将在数组中生成

$list= Yii::app()->db->createCommand('select table1.id,table1.name
                                    from table1
                                        inner join table2
                                        on table1.id=table2.id
                                        inner join table3 
                                        on table2.id=table3.id')->queryAll();

$rs=array();
foreach($list as $item){
    //process each item here
    $rs[]=$item['id'];

}
return $rs;

以yii格式

JOIN_TYPE = INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN etc
$query = new Query;
$query  ->select(['SELECT COLUMNS'])  
        ->from('TABLE_NAME_1')
        ->join( 'JOIN_TYPE', 
                'TABLE_NAME_2',
                'TABLE_NAME_2.COLUMN =TABLE_NAME_1.COLUMN'
            ); 
$command = $query->createCommand();
$data = $command->queryAll();