php - Laravel 5.4 在数据库中存储多对多关系

标签 php mysql laravel-5 eloquent

我有 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/

相关文章:

Laravel 5 : Job schedule without overlap

php - 使用我自己的 Laravel API 时如何遵循不要重复自己的原则?

c# - 从特定列搜索数据,其中要选取的数据按特定列中的重复项排序

php - 如何使用简单的 php 更新 codeigniter ia 中的字段,工作正常,请检查其

php - 哪个数据库设计更好?

javascript - 当我尝试插入两条记录时,CUR_STOCK 表中只有一条记录得到更新?

php - 在 laravel 5.3 中实现命名空间

php - 你如何在 Laravel 默认邮件中自定义变量?

javascript - PHP 动态下拉菜单与 Ajax/JQuery 不工作 --- 正在复制 <head> 代码

php - 如何解析 PHP 中特定分隔部分的字符串?