Laravel拥有多列的AboutToMany枢轴 [英] Laravel belongsToMany pivot with multiple columns

查看:58
本文介绍了Laravel拥有多列的AboutToMany枢轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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?

推荐答案

这很常见,Laravel已经对其进行了处理.在数据透视表中添加额外的列,并扩展您的关系以使用 withPivot():

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

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

然后访问非常简单:

$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

要回答第二部分,该部分本质上是"Triple Pivot",它需要额外的功能.参见

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

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

这篇关于Laravel拥有多列的AboutToMany枢轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆