I have a model related by another one
the schema’s are:
model1: id, default_model2_id (null is permitted)
model2: id, model1_id (is required!)
I want to save them but there is a problem
If the first model when it is new record, there is not id yet to save the second model.
So in this case I save the first model on beforeSave and on afterSave I save the second one and update the first one
-save the first
-save the second (related with the first model id -> now the id exists!)
-update the first one (related with the second model, id just created on the previous line
The problem is the update function invokes the beforeSave again, causing infinite loop!
Does anyone has a robust way to solve this problem?
I could set a flag on the afterSave method to prevent the beforeSave again but I want a better aproach!
First You can save the unique id model2 and then after you can use this unique id and update the modle id
Can you not condition the beforeSave with isNewRecord
I set isNewRecord to false according to another post but not works because beforeSave is called independent of ‘isNewRecord’
I cannot save the model2 before save the model1 because the first one (model2) requires the id of second one (model1)
Ok I found the solution
I migrated the code of beforeSave() to beforeValidate()
I replace $this->update() (or $this->save() or $this->save(false)) with
According to this documentation
saveAttributes not call either beforeSave or afterSave!
May is was not required to migrate my code to beforeValidate(), but for extra reasons I deside to do that.
So the solution was the method ‘saveAttributes’
Thanks for your response!