Laravel 多列的多列数据透视

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49370881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:32:17  来源:igfitidea点击:

Laravel belongsToMany pivot with multiple columns

laravel

提问by hiddenicon

I currently have two tables in the DB and a pivot table to join them when I need to do a belongsToMany lookup. The basic example is one DB table is 'teams' and the other is 'members'. I can utilize the belongsToMany method on both the team and members model to pull their relationship with each other. A team can have many members, and a member can belong to many teams.

我目前在数据库中有两个表和一个数据透视表,当我需要进行belongsToMany 查找时可以将它们连接起来。基本示例是一个数据库表是“团队”,另一个是“成员”。我可以在团队和成员模型上利用belongsToMany 方法来拉取彼此之间的关系。一个团队可以有多个成员,一个成员可以属于多个团队。

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

public function members()
{
  return $this->belongsToMany(Member::class);
}

Pivot: team_member
team_id  |  member_id
---------------------
   1     |      1
   2     |      1
   3     |      2
   1     |      2

How can I expand on that pivot table to include a type of member for each team? For example, member1 is a leader on team1. member1 is an assistant on team2. member1 is a generic member on team3... and so on. Can I just add a column to that same pivot table? Would it be the membertype_id? How can I relate that to another model/table?

我如何扩展该数据透视表以包含每个团队的成员类型?例如,member1 是 team1 的领导者。member1 是 team2 的助手。member1 是 team3 上的通用成员...等等。我可以在同一个数据透视表中添加一列吗?它会是 membertype_id 吗?我如何将其与另一个模型/表格相关联?

回答by Tim Lewis

This is pretty common, and Laravel handles it already. Add extra columns to the pivot table and expand your relationships to use withPivot():

这很常见,Laravel 已经处理了。向数据透视表添加额外的列并扩展您的关系以使用withPivot()

public function teams(){
  return $this->belongsToMany(Team::class)->withPivot(["teamRole", ...]);
}

Then accessing is as simple as:

然后访问就像这样简单:

$user = \App\User::with(["teams"])->first();
$team = $user->teams->first();
$teamRole = $team->pivot->teamRole;

See the Documentation for more information:

有关更多信息,请参阅文档:

https://laravel.com/docs/5.6/eloquent-relationships

https://laravel.com/docs/5.6/eloquent-relationships

To answer the second part, which is essentially a "Triple Pivot", that requires extra functionality. See

回答第二部分,它本质上是一个“三重枢轴”,需要额外的功能。看

Laravel - Pivot table for three models - how to insert related models?

Laravel - 三个模型的数据透视表 - 如何插入相关模型?

for more information, and an associated Package (by the answerer on that question, not maintained, but good for an example)

有关更多信息和相关包(由该问题的回答者提供,未维护,但作为示例很好)

https://github.com/jarektkaczyk/Eloquent-triple-pivot

https://github.com/jarektkaczyk/Eloquent-triple-pivot