P
P
PSmirnov2018-04-03 17:53:38
Yii
PSmirnov, 2018-04-03 17:53:38

How to eager load a nested (cascading) Yii2 relationship?

There are three tables, for example, country (id, country_name), region(id, country_id, region_name), city (id, region_id, city_name), one-to-many relationship. I am outputting data by city in GridView, I managed to set everything up, all filters and sortings work. Only to get the name of the country there are single calls to the database? I suspect the getters need to be changed somehow.
Getter in City:
public function getCountrylName()
{
return $this->region->country->country_name;
}
relationship in City model:
public function getCountry()
{
$query = $this->hasOne(Region::className(), [id' => 'region_id']);
return $query->joinWith('country');
}
If possible, describe the algorithm in more detail, so that there is a direction where to dig, maybe there is a manual on this issue?
Second question. How to organize the default sorting by country_name in the output of cities? Adding 'defaultOrder' => ['country.country_name'=>SORT_ASC] to the CitySearch model in the dataProvider throws an error. If the request for sorting is included in the line for routing, it returns 404.
PS. There is no complete understanding of the structure of the framework yet - I'm studying the second week.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2018-04-03
@webinar

You don't need any join in the links, you need a chain of links and a query like:
or for the dataProvider
, note that country_table_name is the name of the table, not the relationship. The defaultOrder must also contain the table name. You have an error either because of this or because the join was not done.
Join should be removed from the connection. For what you are trying to do there is a viaTable

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question