【问题标题】:Eloquent hasManyThrough also get pivot table recordEloquent hasManyThrough 也获取数据透视表记录
【发布时间】:2015-12-09 15:32:36
【问题描述】:

我的用户模型中有以下关系

public function events($user_id)
{

    return $this->find($user_id)->hasManyThrough('Event', 'Event_Member', 'user_id', 'id');
}

还有三张桌子

用户

id|name|...
1 |bob |
2 |mike|

事件

id|name   |location
1 |meeting|office

Event_Member

user_id|event_id|status
1      |1       |Owner
2      |1       |Guest

hasManyThrough 关系为我提供了来自 Event 表的信息,但我还需要来自数据透视表的状态信息,如何做到这一点?

【问题讨论】:

    标签: php mysql laravel eloquent


    【解决方案1】:

    你所拥有的看起来像是多对多的关系,而不是多对多的关系。您有两个通过数据透视表连接的表,而不是三个父子孙表。

    我强烈建议更改两种模型中的关系。在用户模型中,它看起来像这样:

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

    请注意,数据透视表通常按字母顺序称为model1_model2 - 在这种情况下为event_user。我假设您的数据透视表称为event_members,如果不只是更改它。另请注意,我删除了user_id,因为用户模型已经知道它正在使用哪个用户。

    然后您可以轻松访问数据透视数据,例如像这样:

    foreach ($user->events as $event) {
        echo $event->pivot->status;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-04
      • 2019-09-29
      • 1970-01-01
      • 2015-09-10
      • 2018-03-05
      • 2020-11-09
      • 2016-09-04
      • 2021-02-22
      • 2019-04-27
      相关资源
      最近更新 更多