简体   繁体   English

Yii Framework 2.0关系数据库活动记录

[英]Yii Framework 2.0 Relational Database Active Record

I am working with Yii framework 2.0 and have two database tables (A and B). 我正在使用Yii Framework 2.0,并且有两个数据库表(A和B)。 It is a relational database 1:n. 它是一个关系数据库1:n。 A has only one B but B has many of A. My database looks similar to this. A只有一个B,但是B有许多A。我的数据库与此类似。

A table:
id = 1, name = yes
id = 2, name = no
id = 3, name = ok
id = 4, name = good

B table:
id = 1, a_id = 1
id = 2, a_id = 1
id = 3, a_id = 2
id = 4, a_id = 2
id = 5, a_id = 3

In my controller I use the following code to retrieve all data of A and B: 在我的控制器中,我使用以下代码来检索A和B的所有数据:

$bModel = B::find()->all();

In my view I use the following for-each to echo all the data. 在我看来,我使用以下for-each来回显所有数据。

foreach($bModel as $b) {
   echo $b->a->name . ' - ' $b->id. '<br>;
}

The result is: 结果是:

 yes - 1
 yes - 2
 no  - 3
 no  - 4

What I want is: 我想要的是:

 yes - 1  
       2

 no - 3
      4

I want to merge the a_id and show all the b's id of each merged a_id. 我想合并a_id并显示每个合并的a_id的所有b的ID。 I don't want to use the normal way by firstly get all a's id, use for-each to loop each a's id and then query b one by one by a's id. 我不想使用通常的方法,首先获取所有a的id,使用for-each循环每个a的id,然后按a的id逐一查询b。 How can I approach the second result as I wanted with Yii framework 2.0? 如何使用Yii Framework 2.0达到我想要的第二个结果?

You can use the joinWith() method to eagerly load related models. 您可以使用joinWith()方法来快速加载相关模型。 Eager Loading will fetch all B relations with one query, so that you aren't querying the database each time in the loop. 急切加载将通过一个查询获取所有B关系,因此您不必在循环中每次都查询数据库。 First, ensure that you have this relation defined in model A: 首先,确保在模型A中定义了此关系:

/**
 * @return \yii\db\ActiveQuery
 */
public function getBs()
{
    return $this->hasMany(A::className(), ['a_id' => 'id']);
}

Next, query all of the records together by using the joinWith() method: 接下来,使用joinWith()方法一起查询所有记录:

foreach (A::find()->joinWith('bs')->all() as $a){
    echo $a->name."\n<br />\n";
    foreach ($a->bs as $relatedB){
        echo $relatedB->name.' - '.$relatedB->id."\n<br />\n";
    }
    echo "\n<br />\n";
}

joinWith() defaults to Eager Loading joined models using LEFT JOIN. joinWith()默认为使用LEFT JOIN急切加载联接的模型。 If you run this query and enable database logging, you should only see one query to fetch the A models and one query to fetch the B models. 如果运行此查询并启用数据库日志记录,则应该只看到一个查询以获取A模型,而一个查询则获取B模型。

More about joining with relations: http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#joining-with-relations 有关建立关系的更多信息: http : //www.yiiframework.com/doc-2.0/guide-db-active-record.html#joining-with-relations

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM