/** * Creates a new Content model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Content(['scenario' => Content::SCENARIO_ARTICLE]); if ($model->load(Yii::$app->request->post())) { //事物匿名函数 $callback = function () use($model) { $post = Yii::$app->request->post($model->formName()); if ($model->save() && $model->saveTags($post['tags']) && $model->saveCategory($post['category'])) { return true; } throw new ErrorException('更新数据失败'); }; try { //用数据库事物来保存数据,以免只更新了其中一个 if ($model->getDb()->transaction($callback)) { //如果两个保存成功,则跳转到视图页面预览新增的文章 return $this->redirect(['view', 'id' => $model->id]); } } catch (Exception $e) { Yii::$app->session->setFlash('error', $e->getMessage()); } } return $this->render('create', ['model' => $model]); }