Example #1
0
 /**
  * Updates an existing Post model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id
  * @return mixed
  */
 public function actionUpdate($id)
 {
     $model = $this->findModel($id);
     $model->tags = !empty($model->tags) ? explode(",", $model->tags) : [];
     if (Yii::$app->request->post()) {
         $post = Yii::$app->request->post();
         $category = [];
         if (isset($post['Post']['category'])) {
             $category = $post['Post']['category'];
         }
         if (is_array($post['Post']['tags'])) {
             $post['Post']['tags'] = implode(",", $post['Post']['tags']);
         }
         $model->load($post);
         $transaction = Yii::$app->db->beginTransaction();
         try {
             if ($model->save()) {
                 $cs = BlogCatPos::deleteAll("post_id = :id", ["id" => $model->id]);
                 foreach ($category as $d) {
                     //$c = BlogCatPos::find()->where("post_id = :id AND category_id = :aid",["id"=>$model->id,"aid"=>intval($d)])->one();
                     //if (!$c)
                     //{
                     $c = new BlogCatPos();
                     //}
                     $c->post_id = $model->id;
                     $c->category_id = $d;
                     $c->isdel = 0;
                     $c->save();
                 }
                 $transaction->commit();
                 return $this->redirect(['view', 'id' => $model->id]);
             } else {
                 $transaction->rollBack();
             }
         } catch (Exception $e) {
             $transaction->rollBack();
         }
     }
     return $this->render('update', ['model' => $model]);
 }