With your db scheme - it’s absollutely normal that
$ads[0]->user
is an integer.
It will always be an integer regardless of using eager loading. But it can be confusing.
If you have access to change db scheme and your project isn’t so big - it will be better to rename some columns.
Use
..._id
for foreign key columns.
For example:
Ad
--------
id (primary key)
user_id (foreign key)
It’s more conveniently.
With this db scheme you can write:
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
And then
$ads = Ad::find()->asArray()->all();
var_dump($ads[0]); // array has 'user_id' key (integer), but has no 'user' key
$ads = Ad::find()->with('user')->asArray()->all();
var_dump($ads[0]); // array has 'user_id' key (integer) AND 'user' key (with data from relative User entity)
Thanks a lot. I did the renaming and it’s a lot better now.
Another question:
Assume "ad" entity is related to "building" by a n:1 relation in the DB.Also "building" is related to "district" entity by a m:n relation.
so what I have in my ad model:
public function getBuilding()
{
return $this->hasOne(Building::className(), ['id' => 'building_id']);
}
and in my building model:
public function getAds()
{
return $this->hasMany(Ad::className(), ['building_id' => 'id']);
}
public function getBuildingDistricts()
{
return $this->hasMany(BuildingDistrict::className(), ['building_id' => 'id']);
}
and in my district model:
public function getBuildingDistricts()
{
return $this->hasMany(BuildingDistrict::className(), ['district_id' => 'id']);
}
I want to send Ad information along with it’s building and district information in JSON in an ActiveController. this what I’s doing right now: