/** * Finds the City model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return City the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { $model = Yii::$app->db->cache(function ($db) use($id) { return City::findOne($id); }, Yii::$app->params['dbCacheValidTime']); if ($model !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } }
/** * Сохранение выбранных городов * @param bool $insert * @param array $changedAttributes */ public function afterSave($insert, $changedAttributes) { $oldCities = ArrayHelper::getColumn($this->cities, 'id'); $newCities = empty($this->ids_city) ? [] : $this->ids_city; $diff = array_diff($oldCities, $newCities); foreach ($diff as $idCity) { $city = City::getById($idCity); $this->unlink('cities', $city, true); } $diff = array_diff($newCities, $oldCities); foreach ($diff as $idCity) { $city = City::getById($idCity); $this->link('cities', $city); } parent::afterSave($insert, $changedAttributes); }
/** * Получить город по ключу * @param $idCity * @return mixed * @throws \Exception */ public static function getById($idCity) { return Yii::$app->db->cache(function ($db) use($idCity) { return City::findOne($idCity); }, Yii::$app->params['dbCacheValidTime']); }
/** * Добавление нового города из Кладр через Ajax * @return array */ public function actionCityCreate() { $model = new City(); if ($model->load(Yii::$app->request->post())) { Yii::$app->response->format = Response::FORMAT_JSON; if ($model->save()) { return ['status' => 'success', 'id' => $model->id, 'name' => $model->name]; } else { return $model->getFormattedError(); } } }