php - Laravel 5.4 在数据库中存储多对多关系
问题描述
我有 2 个模型
- 图像请求
- 请求类型
1 个 ImageRequest 可以有很多 RequestType,1 个 RequestType 可以有很多 ImageRequest。
我在我的模型中这样翻译:
图像请求模型:
/**
* Get the Request Types for an image request.
*/
public function requestTypes()
{
return $this->hasMany('App\RequestType');
}
请求类型模型:
/**
* Get the Image Requests for a Request Type.
*/
public function imageRequests()
{
return $this->hasMany('App\ImageRequest');
}
我对 image_requests 表的迁移:
$table->unsignedInteger('request_type_id')->nullable();
$table->foreign('request_type_id')->references('id')->on('request_types');
在我的表单中,我有多个复选框可以在创建新的 ImageRequest 时选择 RequestTypes,如下所示:
@foreach($requestTypes as $requestType)
{{ Form::checkbox('request_type_id', $requestType->id) }}
{{ Form::label($requestType->type, $requestType->type) }}
<br>
@endforeach
我的服务中有一个函数可以存储如下所示的 ImageRequest:
public function storeImageRequest(StoreImageRequestRequest $request)
{
return Auth::user()->imageRequests()->save(new ImageRequest($request->all()));
}
这很好用,但它只存储最后选择的“request_type_id”。它不能存储所有 request_type_id。
如何存储多个 request_type_id?
解决方案
您已将您的关系设置为一对多,阅读多对多的文档。这包括一个用于存储关系的数据透视表。
当您以正确的方式设置数据透视表和关系后,您可以在 ImageRequest 上同步 RequestTypes。
还要更新您的 html 以发布包含所有请求类型 ID 的数组。接下来将所有类型与图像同步。
@foreach($requestTypes as $requestType)
{{ Form::checkbox('request_type_ids[]', $requestType->id) }}
{{ Form::label($requestType->type, $requestType->type) }}
<br>
@endforeach
<?php
$imageRequest = Auth::user()->imageRequests()->save(new ImageRequest($request->all()));
$imageRequest->requestTypes()->sync($request->get('request_type_ids'));
推荐阅读
- c++ - std::unique_ptr 构造函数行为
- javascript - 如何在 Electron 应用退出时关闭 React 应用
- javascript - Material-UI 嵌套复选框选择不会将更改呈现给 DOM 中的父级
- spring-boot - 无法在jenkins中执行spring boot项目
- angular - 我可以使用 MatTable 按选定的行排序吗?
- javascript - 如何使用 foreach 循环创建文本字符串?
- c# - 可空泛型扩展方法
- android - 如何在不同的回收站视图中根据来自firebase的类别加载数据
- grafana - Grafana 中查询的日期计算
- node.js - 如何导出从 Node.js 模块异步加载的日期