【问题标题】:How to setup relationship between 2 table which has both one-to-many and many-to-many relationship?如何在两个同时具有一对多和多对多关系的表之间建立关系?
【发布时间】:2018-10-29 17:47:25
【问题描述】:

我有一个用户表和一个事件表。

它是一对多的关系。

每个用户可以创建许多事件

每个事件都属于一个用户

另外,它还有多对多的关系。

每个用户都可以加入任意数量的活动

每个活动都可以由多个用户加入。

这需要数据透视表。

现在,我被困住了。

这是事件模型。

public function user(){
     return $this->belongsTo('App\User');
}

public function users(){
     return $this->belongsToMany('App\User')
                 ->withTimestamps();
}    

这是用户模型。

public function events(){
     return $this->hasMany('App\Event');
}

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

问题出在用户模型中,我无法定义多个同名函数。

那么,有没有办法正确地做到这一点?

【问题讨论】:

  • 同时显示您的事件和用户表
  • 我不明白你的这句话“问题出在用户模型中,我无法定义多个同名函数。”请解释一下
  • 你的关系是正确的。只需为 events 关系之一使用不同的名称。

标签: laravel model eloquent many-to-many one-to-many


【解决方案1】:

快速解答

当然你不能有两个同名的函数。在您的情况下,请尝试为每个函数使用更具体的名称:

public function createdEvents()
{
     return $this->hasMany('App\Event');
}

public function joinedEvents()
{
     return $this->belongsToMany('App\Event');
}

推荐

您可以使用单个many-to-many 关系来管理与Pivot information 的两个关系:

users

  • id
  • username
  • ...

events

  • id
  • name
  • ...

event_user

  • user_id

  • event_id

  • is_creator(默认FALSE,无符号整数)

  • ...

然后在创建事件时,关联userevent 对象并将is_creator 字段设置为TRUE

所以在你的User 模型中:

app/User.php

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

然后在你的控制器中当你想创建一个事件时:

app/Http/Controllers/SomeCoolController.php

public function store(CreateEventRequest $request)
{
    // Get your event data
    $data = $request->only(['your', 'event', 'fields']);
    // create your object
    $newEvent = Event::create($data);
    // create the relationship with the additional pivot flag.
    auth()->user()->events()->attach($newEvent, ['is_creator' => true]);

    // the rest of your code.
}

当用户想要“加入”一个活动时:

app/Http/Controllers/SomeCoolController.php

public function join(JoinEventRequest $request)
{
    // Get the event
    $event = Event::find($request->event_id);
    // relate the ev
    auth()->user()->events()->attach($newEvent, ['is_creator' => false]);
    // or just this, because its already set to false by default:
    // auth()->user()->events()->attach($newEvent);

    // the rest of your code.
}

【讨论】:

    【解决方案2】:

    UserEvent 之间似乎存在多对多关系,所以会有像 user_event 这样的枢轴名称

    用户模型

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

    参考:https://laravel.com/docs/5.7/eloquent-relationships#many-to-many

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-26
      • 2017-12-28
      • 1970-01-01
      • 1970-01-01
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多