0
votes

I have 3 tables

user

id name

manager

id user_id

projects

id manager_id

From projects model how can I display name in user table.

yii establishes a relation between manager and projects

'managers' => array(self::BELONGS_TO, 'manager', 'manager_id'),

so in the view I can display managers.user_id.

but I can I establish a relation between projects to managers and then to manager to user and get the name of the user in projects table

For example for every manager_id in projects table I want look the user_id for that manager in manager table and then find the user name in User table?

Any help is appreciated. Thanks.

2

2 Answers

0
votes

You should take a look in here. By using 'through' in your relational query, you'll be able to reach the users from the project entity and get all the attributes you wish.

0
votes

You can use two relations back to back to retrieve that info:

$project = Project::model()->with('manager.user')->findByPk((int)$id);
print $project->manager->user->name;

The first line retrieves the project and eager-loads the manager and user information. But even without the eager loading Yii will load things up (it will just take two more database queries). Note also the use of singular names for BELONGS_TO relations. It makes it clearer what is on the other end of the relationship.

I would also recommend considering combining the manager and user tables into one table unless you have a definite need to keep them separate. And then add a isManager boolean value to the User table instead and link manager_id directly to the user table.

If you need a separate model for managers, you could always create a new model for managers that uses the user table, inherits from the User model and define a defaultScope() that filters the managers down by the isManager Boolean value ...

class Manager extends User
{
    public function defaultScope()
    {
        return array(
            'condition'=>'isManager=1',
        );
    }
}

So many cool things to be done with Yii!