Shr*_*gan 1 left-join yii yii2
这是表1
id1 Name
------------
1 value1
2 value2
Run Code Online (Sandbox Code Playgroud)
这是表2
id2 Name id1
---------------------
1 value1 2
2 value2 1
Run Code Online (Sandbox Code Playgroud)
这是表3
id3 Name id2
---------------------
1 value1 2
2 value2 1
Run Code Online (Sandbox Code Playgroud)
这是表4
id4 Name id3
---------------------
1 value1 2
2 value2 1
Run Code Online (Sandbox Code Playgroud)
我想用模型连接 Yii2中的上述 4 个表
select * from table1
left join table2 on table2.id2 = table1.id1
left join table3 on table2.id3 = table1.id2
left join table4 on table2.id4 = table1.id3
Run Code Online (Sandbox Code Playgroud)
第 1 步:声明关系
要使用 Active Record 处理关系数据,首先需要在 Active Record 类中声明关系。任务很简单,只需为每个感兴趣的关系声明一个关系方法,如下所示,
class TableOneModel extends ActiveRecord
{
// ...
public function getTableTwo()
{
return $this->hasMany(TableTwoModel::className(), ['id1' => 'id1']);
}
}
class TableTwoModel extends ActiveRecord
{
// ...
public function getTableThree()
{
return $this->hasMany(TableThreeModel::className(), ['id2' => 'id2']);
}
}
.....
same create table3 and table4 relation
Run Code Online (Sandbox Code Playgroud)
如果使用hasMany()声明关系,则访问此关系属性将返回相关 Active Record 实例的数组;如果使用hasOne()声明关系,则访问关系属性将返回相关的 Active Record 实例,如果未找到相关数据,则返回 null。
步骤 2:访问关系数据
声明关系后,您可以通过关系名称访问关系数据。这就像访问关系方法定义的对象属性一样。因此,我们将其称为关系属性。例如,
$query = TableOneModel::find()
->joinWith(['tableTwo.tableThree'])
->all();
Run Code Online (Sandbox Code Playgroud)
$query = (new \yii\db\Query())
->from('table1 as tb1')
->leftJoin('table2 as tb2', 'tb1.id1 = tb2.id1')
->leftJoin('table3 as tb3', 'tb2.id2 = tb3.id2')
->leftJoin('table4 as tb4', 'tb3.id3 = tb4.id3')
->all();
Run Code Online (Sandbox Code Playgroud)
请参阅查询生成器文档和leftJoin()。