Search code examples
phpyiigiiyii-cactiverecord

Relational Databases in Yii


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')
    );
}

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.