我有 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 时,我有多个复选框来选择 RequestType,如下所示:
@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?
最佳答案
您已将关系设置为一对多,请阅读 docs对于许多对许多。 这包括一个用于存储关系的数据透视表。
以正确的方式设置数据透视表和关系后,您可以同步 ImageRequest 上的 RequestType。
同时更新您的 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'));
关于php - Laravel 5.4 在数据库中存储多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52816511/