Is It Possible To Save Onetomany Relation

Hello :)

I want to save OneToMany relation. Comment has OneToMany relation with user, so user has ManyToOne relation with comment. In code it looks like this:




        $comment = new comment();

        $comment ->content= 'This is ant awesome topic¹';

        $comment ->save();


        $comment->user = User::model()->findByPk(1);

        $comment->save();

Is it possible to do it? Because it looks like the property comment->user is readonly.

$model->user is only User object filled

by JOIN relation.

You can set user_id of model and then save,

$model->user_id = 1;

$model->save();

You can iterate over a dataset and save as many as records you want if you trying to save multiple comments for one user and one more thing you should assign the id not the object itself


$user = User::model()->findByPk(1);

$comment = new comment();

$comment ->content= 'This is ant awesome topic¹';

$comment->user = $user->id;

$comment->save();

It’s what I’ve figured out, but I’m used to assign object value to object, instead relating them by using ids (when working with other implementations of active record pattern). So this post was to check if i’m doing something wrong, or it’s not possible.

Thank you! I appreciate time it took you to respond :)

I think more like:


$comment->user_id = $user->id;

because $comment->user returns object of type User (at least in my example).

Thank you for your answer, now I’m sure I must relate objects by using id, but not objects themselves.