Search code examples
yii2yii2-validation

yii2 validate related models


We have 2 models:

  • Order
  • OrderItems

So when saving the related OrderItems I need to check some attributes from the parent Order.

Order has attributes: "time_begin" and "time_end" and OrderItem has its own "time_begin" and "time_end". So the rule is that times of the OrderItem must be between times of the parent Order.

For example, I have the following situation:

  • user changes the "time_end" of the Order to the bigger value and changes the "time_end" of OrderItem to bigger value too
  • try to save all the related data (Order and all its Items)
  • Order validations pass successfully
  • but when the OrderItem trying to validate its "time_end", it takes the old value of Order->time_end property and gives an validation error!!!

Any solution??? How to let OrderItem to know that Order has changed?


Solution

  • It's a complicated issue, you may consider this way: - Don't call Order::validate() and OrderItems::validate() simultaneously. - Order::validate() -> Order::save() first than OrderItems::validate() -> OrderItems::save() (is this failed, remember to revert Order if needed)