在Yii2中使用模型联接表 [英] Join tables using model in Yii2

查看:316
本文介绍了在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

推荐答案

1.使用Yii2 ActiveQuery

第1步:声明关系

要使用Active Record处理关系数据,首先需要在Active Record类中声明关系.任务就像为每个感兴趣的关系声明一个关系方法一样简单,如下所示,

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

如果使用 hasMany声明了关系(),访问此关系属性将返回相关Active Record实例的数组;如果使用 hasOne(),访问关联属性将返回相关的Active Record实例;如果未找到相关数据,则返回null.

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.

第2步:访问关系数据

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

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

引用 yii\db\ActiveQuery .

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

这篇关于在Yii2中使用模型联接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆