How To Add Some Relation Fields To The Model

Hello

I would like to do this, but I am blocked,

I’ve got a model with a relation like this:


class Post extends CActiveRecord

{

    public function relations()

    {

        return array(

            'users'=>array(self::HAS_MANY, 'User', 'userId'),

            

        );

    }

}

and now I have this method to get all post from an user;




public function getUserPost($id){

 $posts = $this->findByPK($id);

var_dump($posts);//here I get all post information relate to user $id

}

But for example I want that in the result of function getUserPost, add also for example username, that is a field that is in user table, but I only have all the fields belongs to model Post, that means all fields from table post in database, but I need also in the result to add one of the relation fields.

My doubt: How can I do that !

Thank you in advance !

It need some changes:




$posts = $this->with('users')->findByPK($id);




Is that OK;)

  1. It is a bit strange that a Post has more than one user, usually it is the other way around;

  2. You could rely on lazy loading by calling ‘$post->users’. That will launch an extra db request when needed.

You’ll notice that:


[size=2]public function getUserPost($id){[/size]

 $posts = $this->findByPK($id);

$posts->users;

var_dump($posts);//here I get all post information relate to user $id

[size=2]}[/size]

will also get you the list of users in the dump (without wit).