How to set related values


From the tutorial documentation about Relational Active Records ( I saw that I can get the related values from a model (following the example on the tutorial) by performing a:


How do I do the opposite? I mean, if I want to create a new $post and associate an $author, how do I do it?

$post->author = $author;

doesn’t seem to work. This works, but is it the right way?

$post->author_id = $author->id;

Thank you…


Yes, it’s the right way.


I believe that at this point in your ‘posting’, $post->author is not set. I think you want to set the author_id to the id of the currently logged user.

$post->author_id = Yii::app()->user->id

*this is assuming you overwrote the getId() function in the UserIdentity class. See the Blog Demo for more information on this.

Hey thanks,

My question was a theoretical one. "If" I create a new $post entity and if I "somehow" have an $author entity how do I set the author of the post?

What you said, obviously is correct, but I was wondering if there was an automagical way to use something like $post->author = $author.

It is clear now. Thanks…