使用其他数据在Laravel中创建多对多关系 [英] Creating a Many-to-many relationship in Laravel with additional data

查看:153
本文介绍了使用其他数据在Laravel中创建多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中有一个数据透视表,用于存储其他信息.它具有2个外键和一个附加字段.看起来是这样的:

I have in my database a pivot table that stores extra information. It has 2 foreign keys, and an additional field. Here's what it looks like:

EventTeam
  int event_id (fk)
  int team_id (fk)
  boolean home

这里的目的是一个事件可能有很多团队(实际上,它必须至少有2个团队,但这不是数据库约束),并且一个团队可以参加很多事件.但是,对于每个事件与团队之间的关系,我还想跟踪团队是否被视为该事件的主队.

The intent here is that an Event may have many teams (in fact, it must have at least 2, but that's not a database constraint), and a team may participate in many events. However, for each event-team relationship, I want to also track whether the team is considered the home team for that event.

我如何牢记这一点来定义我的模型?我是否拥有EventTeam模型,还是在Team和Event模型中都定义了belongsToMany关系?如果我需要一个单独的模型,我应该在其中定义什么关系?如果不这样做,如何将布尔字段添加到要使用的数据透视表中?我真的不知道该怎么做.

How do I define my model with this in mind? Do I have an EventTeam model at all, or do I define a belongsToMany relationship in both the Team and Event models? If I need a separate model, what relationships do I define in it? If I don't, how do I add the boolean field to the pivot table that gets used? I really have no idea how to do this.

推荐答案

您本身不需要EventTeam模型,但是对于播种者来说,或者如果您要将模型附加到EventTeam连接中的其他位置,它可能会派上用场应用程序.这应该起作用:

You dont need a EventTeam model per se, but it could come in handy for seeders or if you are going to attach models to your EventTeam connection anywhere else in your app. This should work:

事件模型:

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

团队模型:

public function events()
{
    return $this->belongsToMany('Event');
}

对于额外的布尔值,您可以使用-> withPivot().

For the extra boolean you can use ->withPivot().

$this->belongsToMany('Event')->withPivot('is_home');

请参见 http://laravel.com/docs/eloquent#working-with -pivot-tables 了解更多信息.

更新后的答案:

1)我会将其同时放在两个模型中,以便您可以从两侧访问数据透视表而没有问题.

1) I would put it in both models so you can access the pivot data from both sides without a problem.

2)应该确实是列名.

2) It should be to column name indeed.

3)就像我说的,在这种情况下,它并不是真正需要的,但是您可以这样做:

3) Like i said its not really needed for you in this situation, but you could do this:

EventTeam模型:

EventTeam model:

public function event()
{
    return $this->belongsTo('Event');
}

public function team()
{
    return $this->belongsTo('Team');
}

这篇关于使用其他数据在Laravel中创建多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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