AR Model validate child relationship on save

I’m looking for a way to validate a parent Ar model, on create and update, has a child relationship to another table. For example, I want to make sure that a “user” has at least one “phone_number” before it is created or updated.

I have an AR model for my "user" table and another for my "phone_number" table. The phone_number table has a foreign key back to the user table. When I create a new user or update an existing one I want to verify that at least one phone number exists for a user. Is there any way to do this?

Hi,

Yes there is a way to do this.

Just make phone number a required attribute…

And validate both models before you actually save them.

(Only save both models, when validation for both models was successfull)

This Yii 1.1 guide can show you a basic example:

http://www.yiiframework.com/wiki/19/how-to-use-a-single-form-to-collect-data-for-two-or-more-models

But of course you have to adapt it for Yii 2…

Regards