user2355734 user2355734 - 1 month ago 17
PHP Question

Yii2 eager loading not working

I have two entities in my database which are related by a one to many relationship: "User" and "Ad"
I have generated model classes using gii.
This is what I have in my model class for User:

public function getAds()
{
return $this->hasMany(Ad::className(), ['user' => 'id']);
}


and for my Ad model:

public function getUser0()
{
return $this->hasOne(User::className(), ['id' => 'user']);
}


according to Yii2 documentation, In the controller when I do

$ads = Ad::find()->all();
var_dump($ads[0]->user);


It should eagerly load user data from the DB but I only get the foreign key (1).
Even when I try

$ads = Ad::find()->with('user0')->all();
var_dump($ads[0]->user);


Its still the same.

thanks. If I want to send Ads and their related user data by xml in an ActiveController, do I have to do something like this:

$t = array();
foreach ($ads as $ad) {
$t[] = [$ad, $ad->user0];
}
return $t;


Or there is a more straightforward way to do that?

Answer

You are still getting Ad objects either with or without eager loading.

The difference is how the relations are populated, with lazy loading the relations are only loaded when they are accessed.

$ads = Ad::find()->all();
foreach ($ads as $ad) {
    var_dump($ad->user0); // query to load user record here
}

With eager loading they are populated up front.

$ads = Ad::find()->with('user0')->all();
foreach ($ads as $ad) {
    var_dump($ad->user0); // user0 already populated, no query
}