Answer the question
In order to leave comments, you need to log in
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] ...
}
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] ...
}
$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(...)] ...
}
Answer the question
In order to leave comments, you need to log in
I use native links in the framework for this.
$city = City::findOne( ... );
$city->region->country
$country = Country::findOne( ... );
foreach( $country->regions as $region ) {
foreach ( $region->cities as $city ) {
echo $city->name
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question