Question

So I've tried this: http://www.yiiframework.com/wiki/285/accessing-data-in-a-join-table-with-the-related-models

Basically I have a table called User which relates to ToolAccess; related via a primary key on User and a field for userID on ToolAccess. Now tool access relates to the table Tool which contains a ToolID. Now this doesn't work in Yii, I can't seem to get the toolName field off of the tool table using Yii. Any ideas on how to do this on a Active Record?

I'm using giix if that matters.

Relations code:

public function relations() {
    return array(
        'usergalleries' => array(self::HAS_MANY, 'Usergallery', 'userid'),
        'userinroles' => array(self::HAS_MANY, 'Userinroles', 'userid'),
        'userfailedlogin' => array(self::HAS_MANY, 'Userfailedlogin','userid'),
        // table name, relation, class name, relation key
        'toolaccess' =>array(self::HAS_MANY, 'Toolaccess','userid'),
        'tool' =>array(self::HAS_MANY, 'Tool','toolid')
    );
}
Was it helpful?

Solution

I'm assuming your schema looks something like this:

User table             tool_access table          Tool table

id | other columns     userid | toolid            id | name | other columns

In this case, the User model should have a relation like this (note that the tools will be ordered by name in this case):

public function relations() {
    return array(
        // other relations here...
        'tools' =>array(self::MANY_MANY, 'Tool', 'tool_access(userid,toolid)',
          'order' => 'tools.name',
        ),
    );
}

and the code to read the tools should look like this:

$user = User::model()->with('tools')->findByPk($id);
foreach($user->tools as $tool) {
    echo $tool->name;
}

I used eager loading of the tools here mostly because of personal preference, using lazy loading should work just as well in this case. But eager loading should be preferred whenever you're processing multiple User records at once.

OTHER TIPS

So if I have understood it properly, user and tool are related in a many-to-many relationship by their primary keys.

So you should define this relationship in the User model like:

'tools' => array(self::MANY_MANY, 'Tool', 'tool_access(userid, toolid)', 'index' => 'id'),

This way you can access the name of the tool after getting the user model

$user = User::model->findByPk($id);
$tools = $user->tools;
foreach ($tools as $tool)
{
    echo $tool->name;
}

I hope it works for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top