首页 > 解决方案 > 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?

标签: phpmysqllaravel-5eloquent

解决方案


您已将您的关系设置为一对多,阅读多对多的文档。这包括一个用于存储关系的数据透视表。

当您以正确的方式设置数据透视表和关系后,您可以在 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'));

推荐阅读