Whiskey Whiskey - 7 months ago 160
PHP Question

Yii2 triggering a model/record update from afterSave

After saving a new model / active record in Yii2, I'm scheduling a job on the filesystem. I do this in afterSave and I would like to update the record with the job id of the scheduler I get back.

But when I call $this->update() in the model after setting the correct property to the job id, no update is happening. Using update() in an afterSave() is probably a bad idea, but what would then be the right way to tackle this?


I see 2 options there:

  1. Create additional internal field in the model, something like private $task_sended = false; In afterUpdate set task_sended = true and check It

    if (!$this->task_sended){ //send task to scheduler $this->task_sended = true; }

  2. Use DAO command to update model

    \Yii::$app->db->createCommand()->update(self::tableName(), $update, ['id'=>$this->id])->execute();