Extend model with new attributes and populate by join query

Hi guys,

looking for a good idea. I have two tables with Models, Group and User - each user has a group id in his record. I want to create a list of users and display their full groupname. And I want to be able to use sorting, paging, filtering. I think this wont work with relations, right?

I could create a view and link that to a new model and that should work.

But my question is, if there is a way to extend the User model and when adding a join statement to the criteria I use to pull the users, make the User model to fill the extra fields from the query.

Or differently said, if I do a find on the User model with criteria that lead to this query

SELECT t_group.*, t_user.* FROM 't_user' LEFT JOIN t_group ON t_group.gid=t_user.gid

can I make t_group’s attributes available through the User model? By default, I only can access the t_user.* fields.



If I understand your problem correct this is a case of basic relational AR similar to the following:

In the User model

public function relations()


  return array(

    'group'=>array(self::BELONGS_TO, 'Group', 'gid'),



In your controller

$userRecord = User::model()->with('group')->find($your-criteria);

In your view

echo $userRecord->group->your-attribute;

Also see:



Hi Tommy,

the one with the relation I already had. Problem is that if you do it like that, it seems to me that you have to implement sorting on the column by yourself. And using eager or lazy loading - it will be a mess.

What I want to do is this

echo $userRecord->group-table-attribute;

I can add the attribute to the User model, but how can I tell the model to populate it with a specific field from the data if the specific field shows up in the data?

I.e., make the attribute available through the model, if the attribute is contained in the dataset.

Perhaps there is a way to access the underlying raw query result and implement an onload event that copies it to the attribute if present.

In standard sql thinking, for this kind of problem I would create a virtual table by using a view and issue a query on this one. So the data would be put together right away. In Yii, it seems to me that I require a model for each view, and may lead to a model flood :)