Search code examples
kohanakohana-3kohana-orm

Kohana ORM relationships question


I have tables:

users {id, name}
projects {id, name}
roles {id, name}
projects_users {id, user_id, project_id, role_id}

I have models:

project { has many users through projects_users }
user { has many projects through projects_users }

Question: How i get user roles for one project? Or maybe i have to reconstruct my tables?

Code:

$project = ORM::factory('project', $id);
$users = $project->users->find_all();
foreach ($users as $u) {
    $roles = $u-> .... How to get all roles for this user and for this project?
}

Solution

  • Your project_users table seems to be representing roles on projects, add another model which is tied to that table:

    project_role { 
        has one user 
        has one role
        has one project
    }
    user {
        has many project_role
        ...
    }
    project {
        has many project_role
        ...
    }
    

    Then you might be able to do:

    $user = ORM::factory('user')
        ->with('project_role')
        ->where('project_role.project_id', '=', $id)
        ->with('project_role:role')->findall();
    

    If that doesn't work, one of the following should work, but may be a different form of traversal to what you're after.

    $project = ORM::factory('project', $id);
    $roles = $project->project_role->with('user')->with('role')->findall();
    

    Or

    $roles = ORM::factory('project_role')
        ->where('project_id', '=', $id)
        ->with('user')->with('role')->findall();