Ejemplo n.º 1
0
 /**
  * Updates an existing Posts 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);
     $relatives = $model->relatives;
     $relativesID = [];
     foreach ($relatives as $relative) {
         $relativesID[] = $relative->id_categories;
     }
     /** @var Categories[] $categories */
     $categories = Categories::find()->all();
     /** @var [] $items [category_id => 'name',category_id => 'name',category_id => 'name'] */
     $items = [];
     foreach ($categories as $category) {
         $items[$category->id] = $category->title;
     }
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
         $model->unlinkAll('relatives', true);
         foreach ($model->categoriesID as $categoryID) {
             $categoryPost = new Relatives();
             $categoryPost->id_categories = $categoryID;
             $categoryPost->id_posts = $model->id;
             $categoryPost->save();
         }
         return $this->redirect(['view', 'id' => $model->id]);
     } else {
         $model->categoriesID = $relativesID;
         return $this->render('update', ['model' => $model, 'items' => $items]);
     }
 }
Ejemplo n.º 2
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getRelatives()
 {
     return $this->hasMany(Relatives::className(), ['id_categories' => 'id']);
 }