在 Yii2 中使用模型连接表

Join tables using model in Yii2

这是表 1

id1  Name
------------
 1   value1
 2   value2

这是表 2

id2  Name     id1
---------------------
 1   value1    2
 2   value2    1

这是表 3

id3  Name     id2
---------------------
 1   value1    2
 2   value2    1

这是表 4

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

使用Gii生成模型,如果外键在数据库中定义好,那么关系就会在你的模型中生成。如果没有,那么您可以自己定义关系。 See it here how to define those relations in a Yii2 model.
然后你应该能够通过这样做来访问模型 Table4 的属性:

$table1 = Table1::findById(1);

var_dump($table1->table2->table3->table4->attributes);

1。使用 Yii2 ActiveQuery

第一步:声明关系

要使用 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

如果关系是用 hasMany(), accessing this relation property will return an array of the related Active Record instances; if a relation is declared with hasOne() 声明的,访问关系 属性 将 return 相关的 Active Record 实例,如果没有找到相关数据则为 null。

第 2 步:访问关系数据

声明关系后,可以通过关系名访问关系数据。这就像访问由关系方法定义的对象 属性 一样。因此,我们称它为关系 属性。例如,

$query = TableOneModel::find()
           ->joinWith(['tableTwo.tableThree'])
           ->all();

参考yii\db\ActiveQuery.

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();

参考Query Builder documentation and leftJoin().