简体   繁体   English

获取有关枢轴列[Laravel 5]的详细信息

[英]Get details about pivot column [Laravel 5]

I have 3 tables: Project , Group , User 我有3个表: ProjectGroupUser

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_iduser_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM