php - Laravel belongsToMany 检索多于一行
问题描述
所以我创建了一个预订系统,您可以在其中创建地图并将它们分配给一个活动。我有 3 张桌子来处理这个events
,,,maps
和event_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
.
其他一切都按预期工作。
谁能收拾这个烂摊子?:)
解决方案
id
s 在关系中是倒置的。试试这个:
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',
);
}
推荐阅读
- javascript - 如何将数组拆分为奇数数组和偶数数组
- sql - 在运行平均值中添加额外的分组依据
- android - Android Studio原生调试不起作用,总是显示“此文件不是项目的一部分”
- r - 重塑 ggradar 中的组标签
- python - 两个随机分布python的差异
- tensorflow - 数据集不平衡时多类分类的最佳损失函数?
- python - 无法获取 HTML 标记内的数据
- android - 如何删除 FloatingActionButton 中的填充图标
- code-signing - 是否可以在没有 mac 应用商店的情况下分发签名的 mac 应用程序(使用免费开发帐户)?
- azure-iot-hub - Azure IoT 设备预配接口规范