I do a sample of the city, the city has areas, they have complexes, and the complexes have apartments. In the end, I need to get apartments for a particular city, indicating the associated filters (district, complex, etc.). At the moment I did this:
public function actionIndex() { $cities = Cities::find()->where(['id' => Yii::$app->request->get('city_id')])->with([ 'districts' => function ($query){ $query->filterWhere([ 'id' => Yii::$app->request->get('district_id'), ]); }, 'districts.complexes' => function ($query) { $query->filterWhere([ 'id' => Yii::$app->request->get('complex_id'), 'type_id' => Yii::$app->request->get('complex_type_id'), 'developer_id' => Yii::$app->request->get('developer_id'), ]); }, 'districts.complexes.apartments' => function ($query) { $query->filterWhere([ 'amount_room' => Yii::$app->request->get('amount_room'), 'yardage' => Yii::$app->request->get('yardage'), 'level' => Yii::$app->request->get('level'), 'price' => Yii::$app->request->get('price'), ]); }, ])->all(); $query = []; foreach ($cities as $city) { foreach ($city->districts as $district) { foreach ($district->complexes as $complex) { foreach ($complex->apartments as $apartment) { $query[] = $apartment; } } } } return new ArrayDataProvider([ 'allModels' => $query, ]); } But it looks like a crutch, maybe I went the wrong way, and can I do better?