/** * After saving the action, it deletes the joined devices from * this action, then it save all the devices joined to this action * * @param type $insert * @param type $changedAttributes */ public function afterSave($insert, $changedAttributes) { // get all the devices joined with this action // loop through them and determine what to do with them // if the don not exists in the device_ids delete it $deviceaction = $this->getDeviceActions(); foreach ($deviceaction as $device_id) { if (!in_array($device_id, $this->device_ids)) { $devact = DeviceAction::find()->where(['device_id' => $device_id, 'action_id' => $this->id])->one(); if (!$devact->delete()) { print_r($devact->errors); exit; } } } // loop trough the device_ids, if the don not exists in the deviceaction // save it foreach ($this->device_ids as $device_id) { if (!in_array($device_id, $deviceaction)) { $devact = new DeviceAction(); $devact->device_id = $device_id; $devact->action_id = $this->id; $devact->created_at = new Expression('NOW()'); if (!$devact->save()) { print_r($devact->errors); exit; } } } parent::afterSave($insert, $changedAttributes); }