Join tables using model in Yii2

隐身守侯 提交于 2020-01-06 09:06:12

问题


this is table1

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

this is table2

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

this is table3

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

this is table4

id4  Name     id3
---------------------
 1   value1    2
 2   value2    1

I Want to join above 4 tables in Yii2 with model

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

回答1:


1. Use Yii2 ActiveQuery

Step-1 : Declaring Relations

To work with relational data using Active Record, you first need to declare relations in Active Record classes. The task is as simple as declaring a relation method for every interested relation, like the following,

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

If a relation is declared with hasMany(), accessing this relation property will return an array of the related Active Record instances; if a relation is declared with hasOne(), accessing the relation property will return the related Active Record instance or null if no related data is found.

Step-2 : Accessing Relational Data

After declaring relations, you can access relational data through relation names. This is just like accessing an object property defined by the relation method. For this reason, we call it relation property. For example,

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

Refer yii\db\ActiveQuery.

2. Use Yii2 DB Query

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

Refer Query Builder documentation and leftJoin().




回答2:


Use Gii to generate models, and if the foreign keys are defined well in the database, then the relations will be generated in your models. If not, then you can define the relations yourself. See it here how to define those relations in a Yii2 model.
Then you should be able to access an attribute of the model Table4 by doing this:

$table1 = Table1::findById(1);

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


来源:https://stackoverflow.com/questions/51284947/join-tables-using-model-in-yii2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!