首页 > 解决方案 > Laravel belongsToMany 检索多于一行

问题描述

所以我创建了一个预订系统,您可以在其中创建地图并将它们分配给一个活动。我有 3 张桌子来处理这个events,,,mapsevent_maps

在阅读了 Laravel 文档后,我决定建立一个 belongsToMany 关系。

但是当我尝试通过我的事件模型检索我的地图时,我只能在第一行得到一个。

在我的控制器中我做

public function displayForm($id)
{
    $event = EventModel::find($id);
    print_r($event->maps);
}

结果是一个 Illuminate\Database\Eloquent\Collection 对象,其中包含 2 张地图中的最后一张,而我终生无法弄清楚如何获得所有地图。

我的活动模型

public function maps()
{
    return $this->belongsToMany('App\Models\Booky\MapsModel',
        // Table name of the relationship's joining table.
        'event_maps',
        // Foreign key name of the model on which you are defining the relationship
        'map_id',
        // Foreign key name of the model that you are joining to
        'event_id'
    );
}

我的地图模型

public function event()
{
    return $this->belongsToMany('App\Models\Booky\EventsModel',
        // Table name of the relationship's joining table.
        'event_maps',
        // Foreign key name of the model on which you are defining the relationship
        'event_id',
        // Foreign key name of the model that you are joining to
        'map_id'
    );
}

数据库看起来像这样

events
  - id
  - lots of irrelevant data
maps
  - id
  - lots of irrelevant data
event_maps
  - id
  - event_id
  - map_id

我在想也许我应该使用另一种关系类型,但据我所知,他们不使用像event_maps.

其他一切都按预期工作。

谁能收拾这个烂摊子?:)

标签: phplaraveleloquent

解决方案


ids 在关系中是倒置的。试试这个:

public function maps()
{
    return $this->belongsToMany('App\Models\Booky\MapsModel',
        // Table name of the relationship's joining table.
        'event_maps',
        // Foreign key name of the model that you are joining to
        'event_id'
        // Foreign key name of the model on which you are defining the relationship
        'map_id',
    );
}

和:

public function event()
{
    return $this->belongsToMany('App\Models\Booky\EventsModel',
        // Table name of the relationship's joining table.
        'event_maps',
        // Foreign key name of the model that you are joining to
        'map_id'
        // Foreign key name of the model on which you are defining the relationship
        'event_id',
    );
}

推荐阅读