开发者

Kohana ORM relationships question

开发者 https://www.devze.com 2023-01-10 15:06 出处:网络
I have tables: users {id, name} projects {id, name} roles {id, name} projects_users {id, user_id, project_id, role_id}

I have tables:

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

I have models:

pro开发者_C百科ject { 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?
}


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消