我有桌子:
users {id, name} projects {id, name} roles {id, name} projects_users {id, user_id, project_id, role_id}
我有模特:
project { has many users through projects_users } user { has many projects through projects_users }
问题: 我如何获得一个项目的用户角色?或者我可能需要重建我的桌子?
代码:
$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? }
答案 0 :(得分:1)
您的project_users表似乎代表了项目中的角色,添加了与该表绑定的另一个模型:
project_role {
has one user
has one role
has one project
}
user {
has many project_role
...
}
project {
has many project_role
...
}
然后你可能会这样做:
$user = ORM::factory('user')
->with('project_role')
->where('project_role.project_id', '=', $id)
->with('project_role:role')->findall();
如果这不起作用,则下列其中一项应该有效,但可能是与您所追求的不同的遍历形式。
$project = ORM::factory('project', $id);
$roles = $project->project_role->with('user')->with('role')->findall();
或者
$roles = ORM::factory('project_role')
->where('project_id', '=', $id)
->with('user')->with('role')->findall();