public function afterSave($insert, $changedAttributes) { $selected = Yii::$app->request->post('PostCategory'); \backend\models\PostCategory::deleteAll(['post_id' => $this->id]); $insert_data = []; if (count($selected) > 0) { foreach ($selected as $v) { $insert_data[] = [$this->id, $v]; } Yii::$app->db->createCommand()->batchInsert('post_category', ['post_id', 'category_id'], $insert_data)->execute(); } }
/** * @return \yii\db\ActiveQuery */ public function getPostCategories() { return $this->hasMany(PostCategory::className(), ['post_id' => 'id']); }