简体   繁体   English

Yii2(PHP)中的Active Record:使用关系访问其他数据库表

[英]Active Record in Yii2 (PHP) : access other DB tables with relations

I'm trying to use the Relational Data feature of Active Record in a project in which I'm using the Yii2 framework. 我正在尝试在使用Yii2框架的项目中使用Active Record的关系数据功能。 I have a many to many relation declared between two tables ("post" and "result"). 我在两个表之间声明了多对多关系(“ post”和“ result”)。 When I try to access the data, it works well this way : 当我尝试访问数据时,这种方式可以很好地工作:

$post = Post::findOne(id);
$result= $post->result;

My problem comes up when I need a third table to be involved. 当我需要涉及第三张桌子时,我的问题浮出水面。 I declared (in my models) a many-to-one relation between the "result" table and another table ("weather"). 我在模型中声明了“结果”表和另一个表(“天气”)之间的多对一关系。

In ResultController : 在ResultController中:

public function getWeather() {
    return $this -> hasOne(\modules\custom\models\Weather::className(), ['id' => 'weather_id']);
}

In WeatherController : 在WeatherController中:

public function getResult() {
    return $this -> hasMany(\modules\custom\models\Result::className(), ['cube_id' => 'id']);
}

Once I access the data from "post" and "result" like mentionned above, is it possible to also access the data from "weather" that is linked to "result" via the relation? 一旦我如上所述从“发布”和“结果”访问数据,是否也可以通过关系从“天气”访问链接到“结果”的数据? If not, what would be the best way to get the data from the 3rd table? 如果不是,从第三张表中获取数据的最佳方法是什么?

If you are using Post Model as primary in query then you have to create relation in Post model. 如果您在查询中使用邮政模型作为主要模型,则必须在邮政模型中创建关系。 There are two scenario : 1. Such as Post Model has relation with Result and Weather model then you have to write query like this 有两种情况:1.例如Post Model与Result和Weather模型有关,那么您必须像这样编写查询

$post = Post::find()->joinWith(['result','weather'])->andWhere(['id'=>$id])->one;

2. If Post model has relation with only Result and Result has relation with Weather then query will be like this: 2.如果Post模型仅与Result相关,而Result与Weather相关,则查询将如下所示:

$post = Post::find()->joinWith(['result','result.weather'])->andWhere(['id'=>$id])->one;

You can add multiple relations within a same query. 您可以在同一查询中添加多个关系。

I figured out something else. 我发现了其他东西。 I was trying to get something more like this: 我试图得到更多这样的东西:

$post = Post::findOne(id);
$result = $post->result;
$weather = $result->weather;

But it wouldn't work. 但这是行不通的。 I found out that the second line returns an array of objects into my $result variable so the third line wouldn't work. 我发现第二行将对象数组返回到$ result变量中,因此第三行不起作用。 I don't know if there is a better way to do it, but I went this way : 我不知道是否有更好的方法,但是我这样做了:

$weather= [];
for ($i = 0; $i < count($result); $i++) {
    array_push($weather, $result[$i]->weather);
}

It anyone knows a cleaner way to do it, let me know! 任何人都知道一种更清洁的方法,请告诉我!

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

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