Saving Multiple, Related Models Simultaneously

Hello and a pre-emptive thank you.

If for example I have 2 or more related models, each of which I stored in its own database table; i.e. user and message.

A ‘user’ row has a relation to an ‘message’ row in the database, using foreign keys.

What I find myself doing a lot is something similar to below, I first save the $user model and then pass the $user->id to the $message model before saving:

$user = new User();

$message = new Message();



$message->userid = $user->id;


Seeing that I have relations defined between user and message is there a clean way I can just ‘save’ and all the models are saved in tandem, therefore negating the need to pass my message model the userid first? It’s this little shuffle at the end I keep finding myself doing again-and-again.

I’m using Yii v1 and still feeling my way around!

You probably have to create a tailored implementation through setters, getters and ‘beforeSave()’. I’ve done so in one occasion. I get the relation from the database on the first ‘set’, update the relation for subsequent sets, and save the relation in a ‘beforeSave()’ or ‘afterSave()’ - and I probably should do that in a transaction starting in the ‘beforeSave’ and ending in the ‘afterSave’.

Another method I used, prior to what I just explained is in the attached file. I created an extension to _RelationAR in which setAttribute and beforeSave are replaced. It is used in production, but only for one Model. The code is not cleaned up and there is still one ‘TODO’ in it (which is not important for my current use of it).

I may have started from some suggestion made on this site somewhere - I am not sure of that. I am sure thought that I have spent some intensive time improving and generalizing this code.

Anyway, it is a start at trying to generalize saving relations.