/** * Aligns the given group selection with the db * @return boolean */ public function afterSave($insert, $changedAttributes) { //Check old group selection and remove non selected groups foreach ($this->currentGroups as $userGroup) { if (!$this->isInGroupSelection($userGroup)) { $this->getGroupUsers()->where(['group_id' => $userGroup->id])->one()->delete(); } } $this->groupSelection = $this->groupSelection == null ? [] : $this->groupSelection; //Add all new selectedGroups to the given user foreach ($this->groupSelection as $groupId) { if (!$this->isCurrentlyMemberOf($groupId)) { Group::findOne($groupId)->addUser($this); } } return parent::afterSave($insert, $changedAttributes); }