public function afterSave($insert, $changedAttributes) { //delete all $models = $this->getCategories()->all(); foreach ($models as $model) { $model->delete(); } if (!empty($this->categoriesList)) { //add new rows foreach ($this->categoriesList as $categoryId) { $model = new FinancePageCategories(); $model->finance_page_id = $this->id; $model->category_id = $categoryId; $model->save(); } } return parent::afterSave($insert, $changedAttributes); }