[英]Laravel 5.4 store Many to Many relationship in database
我有2个型号
1个ImageRequest可以具有许多RequestType,而1 RequestType可以具有许多ImageRequest。
我在模型中这样翻译:
ImageRequest模型:
/**
* Get the Request Types for an image request.
*/
public function requestTypes()
{
return $this->hasMany('App\RequestType');
}
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上的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'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.