alextouzel
alextouzel

Reputation: 238

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. I have a many to many relation declared between two tables ("post" and "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 :

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

In 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?

Upvotes: 0

Views: 594

Answers (2)

alextouzel
alextouzel

Reputation: 238

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. 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!

Upvotes: 0

Deep Swaroop Sachan
Deep Swaroop Sachan

Reputation: 148

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

$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:

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

You can add multiple relations within a same query.

Upvotes: 0

Related Questions