[英]Get details about pivot column [Laravel 5]
I have 3 tables: Project
, Group
, User
我有3个表:
Project
, Group
, User
and one relation pivot table: project_group
with colmuns: id
project_id
group_id
and pivot field user_id
一个关系枢纽表:
project_group
和colmuns: id
project_id
group_id
和枢纽字段user_id
I know how to take all Groups and Projects: 我知道如何参加所有小组和项目:
Project::find(1)->groups()->get();
groups()
is belongToMany function inside Project Model. groups()
是Project Model中的归属函数。
Problem is I don't know how to get all users for particular project. 问题是我不知道如何获得特定项目的所有用户。 I need to get project and all users names and ids for that project, any solution for this?
我需要获取项目以及该项目的所有用户名和ID,对此有什么解决方案?
Thanks in advance 提前致谢
You can try on your Project.php
model adding a pivot relationship 您可以尝试在
Project.php
模型中添加枢纽关系
public function users() {
return $this->hasMany(App\User::class, 'project_group');
}
However this may be misleading as project_group
should be a pivot table between the project
table and the group
table. 但是,这可能会引起误解,因为
project_group
应该是project
表和group
表之间的数据透视表。 user_id
doesn't belong in there. user_id
不属于其中。
Create a second pivot table called group_user
with group_id
, user_id
. 使用
group_id
和user_id
创建另一个名为group_user
数据透视表。 Then you can use this on your Group.php
model: 然后,您可以在
Group.php
模型上使用它:
public function users() {
return $this->hasMany(App\User::class, 'group_user');
}
An example would then be: 然后是一个示例:
$project = Project::find(1);
foreach($project->groups as $group) {
$users = $group->users; // Now you should have access to all the users for each group
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.