Question

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?

Was it helpful?

Solution 2

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();

OTHER TIPS

You can use updateAttributes($attributes)

This method is a shortcut to update() when data validation is not needed and only a small set attributes need to be updated.

You may specify the attributes to be updated as name list or name-value pairs. If the latter, the corresponding attribute values will be modified accordingly. The method will then save the specified attributes into database.

Note that this method will not perform data validation and will not trigger events.

http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#updateAttributes()-detail

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top