A
A
Alex Ershov2015-06-04 14:23:54
Yii
Alex Ershov, 2015-06-04 14:23:54

What is the best way to build a tree with cities in Yii2?

The task arose to build cities in a tree structure. I see 3 options to do it
Arrays

$counties = Country::find()->asArray()->all();
    $districts = District::find()->asArray()->all();
    foreach (City::find()->all() as $city) {
        $cities [$this->getCountryName($counties, $city->country_id)]
        ... [districts][regions] ...
    }

AR objects
foreach (City::find()->all() as $city) {
        $counties = Country::findOne($city->country_id);
        $region = Region::findOne($city->region_id);
        $cities [$county->name] //forming array
        ... [$region->name][regions] ...
    }

Use DataProvider
$counties = new ActiveDataProvider(['query'=> Country::find()])
    $districts = new ActiveDataProvider(['query'=> District::find()])
    foreach (City::find()->all() as $city) {
        $cities [$counties->query-select(...)]
        ... [$counties->query-select(...)] ...
    }

I have now implemented it in the 2nd way, with AR objects, but the page takes a long time to load, for only 3500 cities. I also tried with arrays, it also took a long time to load (all tests on localhost)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly Khomenko, 2015-06-04
@kilimandjaro

I use native links in the framework for this.

$city = City::findOne( ... );
$city->region->country

or vice versa
$country = Country::findOne( ... );
foreach( $country->regions as $region ) {
    foreach ( $region->cities as $city ) {
        echo $city->name
    }
}

Don't forget about eager loading with() and caching via Yii::$app->db->cache( function () {} ) using dependencies.
Added:
1. Read about bindings: www.yiiframework.com/doc-2.0/guide-db-active-recor...
2. Read about eager and lazy loading: www.yiiframework.com/doc-2.0/guide-db -active-recor...
3. Read about caching query results: www.yiiframework.com/doc-2.0/guide-caching-data.ht...
4. Read about dependencies: www.yiiframework.com/doc-2.0 /guide-caching-data.ht...

P
Puma Thailand, 2015-06-04
@opium

Connect the cache, well, think about the logic

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question