简体   繁体   English

与自定义数据透视表的多对多关系

[英]Many to Many Relation with custom pivot table

I have 4 tables in project's database:我在项目的数据库中有 4 个表:

users (id, name)
teams (id, name)
team_members (id, user_id, team_id)
team_member_permissions (team_member_id, team_id)

I need to get user's teams.我需要获得用户的团队。 My current solution is to create teamMembers relationship in User model:我目前的解决方案是在User模型中创建teamMembers关系:

public function teamMembers()
{
    return $this->hasMany(TeamMember::class);
}

members relationship in Team model: Team模型中的members关系:

public function members()
{
    return $this->hasMany(TeamMember::class);
}

permissions relationship in TeamMember model: TeamMember模型中的permissions关系:

public function permissions()
{
    return $this->belongsToMany(Permission::class);
}

But how can I optimise it?但是我该如何优化它呢? For example, to get all teams for users I need to use例如,要为我需要使用的用户获取所有团队

Team::whereHas('teamMember', function($query) use ($user){
    $query->where('user_id', $user->id);
})->paginate();

But how can I implement a relationship that will contains all user's teams to get user's teams in one string of code, like $user->teams ?但是我如何实现一个包含所有用户团队的关系,以便在一个代码字符串中获取用户的团队,比如$user->teams

I suggest you use many to many relation in regards to your team_members tables to explicitly mention as pivot.我建议您对 team_members 表使用多对多关系来明确提及作为枢轴。

User model:用户模型:

public function teams()
{
    return $this->belongsToMany(Team::class, 'team_members');
}

Team model:团队模式:

public function users()
{
    return $this->belongsToMany(User::class, 'team_members');
}

Since you want to use whereHas clause on teamMember table, I believe that you want to extract teams based on the fact that all teams belonging to that user based on team_members table.由于您想在 teamMember 表上使用 whereHas 子句,我相信您想根据属于该用户的所有团队基于 team_members 表来提取团队。

So, You can specify the table name on many to many relation as above.因此,您可以如上所述在多对多关系上指定表名。

Now you can use现在你可以使用

$user->teams

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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