There are three tables: County (id, name), Sity (id, name, country_id), Street (id, name, sity_id)

Country Sity Steet id name id name country_id id name sity_id 1 Россия 1 Москва 1 1 Арбат 1 
  • Question 1. How can I, turning through the Street model, get such an entry: Russia Moscow, ul. Arbat

  • Question 2. How can I get all the Cities and streets of these cities using the Country model. In the Internet and in the documentation I met the following code:

    public function getItems() { return $this->hasMany(Item::className(),['id'=>'item_id'])->via('orderItems'); }

I don’t know if it suits me and I don’t understand how to work with him either. Explain, please.

  • That's right - the city. - Alexey Ukolov
  • @ AlekseyUkolov code is not so live for example. What you wrote is it important? - Sergalas
  • Of course, this is not directly related to the question, but I believe that it is still important. This is the culture and purity of the code, and these things directly wag how long the code will live. - Alexey Ukolov
  • @ AlekseyUkolov I have already explained that these are examples taken from the ceiling, Or should I ask the front of the petition for the fact that I did not write the word city in English? - Sergalas
  • You explained and asked a question. I answered your question. Don't you think it's time to stop the discussion? I pointed out the mistake, you have the right to ignore my comment, you have the right to ask for forgiveness - do what you want, but you do not need to drag me into it. - Alexey Ukolov

1 answer 1

First of all, you should always read the official documentation , your example is moving in the right direction, but wrong, there are 2 ways in the documentation:

 class Order extends ActiveRecord { public function getItems() { return $this->hasMany(Item::className(), ['id' => 'item_id']) ->viaTable('order_item', ['order_id' => 'id']); } } 

or

 class Order extends ActiveRecord { public function getOrderItems() { return $this->hasMany(OrderItem::className(), ['order_id' => 'id']); } public function getItems() { return $this->hasMany(Item::className(), ['id' => 'item_id']) ->via('orderItems'); } } 

That is, in the second example, without the getOrderItems() function, you cannot use via() .