我是table1
id1 Name
------------
1 value1
2 value2
我是table2
id2 Name id1
---------------------
1 value1 2
2 value2 1
我是table3
id3 Name id2
---------------------
1 value1 2
2 value2 1
我是table4
id4 Name id3
---------------------
1 value1 2
2 value2 1
我想将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
发布于 2018-07-11 04:49:36
1.使用Yii2 ActiveQuery
Step-1:声明关系
要使用活动记录处理关系数据,首先需要在活动记录类中声明关系。任务很简单,只需为每个感兴趣的关系声明一个关系方法,如下所示,
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
如果用hasMany()声明关系,则访问该关系属性将返回相关活动记录实例的数组;如果用hasOne()声明关系,则访问关系属性将返回相关的活动记录实例,如果没有找到相关数据,则返回null。
Step-2:访问关系数据
声明关系之后,可以通过关系名称访问关系数据。这就像访问关系方法定义的对象属性一样。因此,我们称它为关系属性。例如,
$query = TableOneModel::find()
->joinWith(['tableTwo.tableThree'])
->all();
2.使用Yii2数据库查询
$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();
请参考查询生成器文档和leftJoin()。
发布于 2018-07-11 04:08:22
使用Gii生成模型,如果外键在数据库中定义得很好,那么这些关系将在您的模型中生成。如果没有,那么你可以自己定义关系。请参见如何在Yii2模型中定义这些关系。
然后,您应该能够通过这样做来访问模型Table4的属性:
$table1 = Table1::findById(1);
var_dump($table1->table2->table3->table4->attributes);
https://stackoverflow.com/questions/51284947
复制相似问题