Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Changing related entities in the events (beforeValidation, beforeSave...)

I've made a behavior, that updates related entities according to some programming logic. I would like to do this inside an event, that is called during save() process, because I do some validation as well and I need to cancel save on errors. But apparently related values are locked on save, and any changes I do are discarded.

public function beforeSave() {
    $related = new Related();
    $related->name = "related";
    $this->related = array($related);
    echo "Called";
}

Works:

$model->beforeSave();
// or $model->getModelsManager()->notifyEvent("beforeSave", $model);
$model->save();

Doesn't work:

$model->save();

I see "Called" in both cases, so method is executed. The model itself is getting saved, but the related object is not saved. Is there any way to change related entities during save process?



81.8k
Accepted
answer

Related entities can't be added in events, these act as the triggers in a database system, you can add records that originally change the execution plan for an specific operation.

To dispatch an operation the ORM does the following:

1) Check if there record does exist in the persistance 2) Check if there are related records added to instance 3) Perform validations to ensure the data can be saved properly 3) According to the previous information the instance will save the related records before saving the instance of after saving the instance

Adding more related records in beforeSave/beforeCreate/beforeUpdate would not work because at those points the execution plan was already designed



7.5k

Thank you for the answer. I presume, that at beforeValidation point execution plan is also already designed, because it acts the same. Do you have any plans to make an event before this operation, to make injections of operations with related entities possible? I'm sure this will be a demanded feature for those who make complex behaviors.