S
S
Sergey Beloventsev2016-05-06 10:03:37
Yii
Sergey Beloventsev, 2016-05-06 10:03:37

How to sequentially link three tables?

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 get the following record using the Street model: Russia, Moscow, st. Arbat
Question 2 How can I get all the Cities and streets of these cities by accessing the Country model. In the vastness of the Internet and in the documentation I came across this code
public function getItems()
        {
            return $this->hasMany(Item::className(), ['id' => 'item_id'])
                ->via('orderItems');
        }

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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Natarov, 2016-05-06
@Sergalas

The code you posted is an intermediate table that implements a many-to-many relationship. And this is not your case. In this case, it turns out that the City of Moscow belongs to both Russia and any other countries. And Other countries have the city of Moscow.
You have one-to-many relationships. Those.
1) One country (one) has many cities (many).
2) One city (one) has many streets (many).

class Country extends ActiveRecord
{
    // HasMany - указывает на то, что получаемое будет множество.
    public function getСities()
    {
        return $this->hasMany(City::className(), ['country_id' => 'id']);
    }
}

class City extends ActiveRecord
{
    public function getCountry()
    {
         //HasOne - показывает, что получаемая запись одна 
        return $this->hasOne(Counter::className(), ['id' => 'country_id']);
    }
}

in fact, you prescribe this in the models that I indicated above, and not shove everything into one.
By analogy, you will do between the city and the streets.
This is how you get all the cities that belong to one country.
$country = Country::findOne(1); // ищем город с id 1

// SELECT * FROM `City` WHERE `country_id` = 1
// $сities - это массив объектов City
$сities = $country->сities; // Обратите внимание, что в модели города, есть Getter и именно то название.

To get nested links, it is better to use eager loading (pulling all links with one request, because it is less resource-intensive than pulling out only the right one ten times.)
$countries = Country::find()->with('cities.streets')->all(); // внутри With помещены геттеры связей.
// ниже код, запрос в базу не делает. он вытаскивает все из запроса то что выше. т.е. экономит вашу память и бережет БД. 
$streets = $countries[0]->cities[0]->streets; // указывая массивы можно вызвать конкретную страну с конкретным городом и получить нужные улицы.

You can also make a custom request using anonymous functions. in which to substitute the necessary values ​​of the Country, City, street - thereby pulling out something specific
PS Pay attention to the name of the Getters, they are in the singular where the connection is one and in the plural where there are many. Don't forget good naming. This way you won't get confused in your connections. Good luck )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question