简体   繁体   English

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

[英]Laravel 5.4 store Many to Many relationship in database

I have 2 models 我有2个型号

  • ImageRequest ImageRequest
  • RequestType 请求类型

1 ImageRequest can have Many RequestTypes and 1 RequestType can have Many ImageRequests. 1个ImageRequest可以具有许多RequestType,而1 RequestType可以具有许多ImageRequest。

I translated this like this in my models: 我在模型中这样翻译:

ImageRequest Model: ImageRequest模型:

/**
 * Get the Request Types for an image request.
 */
public function requestTypes()
{
    return $this->hasMany('App\RequestType');
}

RequestType Model: RequestType模型:

/**
 * Get the Image Requests for a Request Type.
 */
public function imageRequests()
{
    return $this->hasMany('App\ImageRequest');
}

My migration for the image_requests table: 我对image_requests表的迁移:

$table->unsignedInteger('request_type_id')->nullable();
$table->foreign('request_type_id')->references('id')->on('request_types');

In my form I have multiple checkboxes to select the RequestTypes when creating a new ImageRequest like this: 在我的表单中,当创建这样的新ImageRequest时,我有多个复选框可以选择RequestTypes:

@foreach($requestTypes as $requestType)
    {{ Form::checkbox('request_type_id', $requestType->id) }}
    {{ Form::label($requestType->type, $requestType->type) }}
    <br>
@endforeach

I have a function in my service to store the ImageRequest that looks like this: 我的服务中有一个函数可以存储如下所示的ImageRequest:

public function storeImageRequest(StoreImageRequestRequest $request)
{
    return Auth::user()->imageRequests()->save(new ImageRequest($request->all()));
}

This works great but it only stores the last "request_type_id" selected. 这很好用,但它只存储最后选择的“ request_type_id”。 It can't store all request_type_id's. 它不能存储所有request_type_id。

How can I store multiple request_type_id's? 如何存储多个request_type_id?

You have setup your relation as a one to many, read the docs for many to many. 您已将一对多关系设置为一对多,阅读了许多对文档 This includes a pivot table to store the relations. 这包括一个存储关系的数据透视表。

When you have setup your pivot table and relations in the right way, you can sync the RequestTypes on the ImageRequest. 以正确的方式设置数据透视表和关系后,可以同步ImageRequest上的RequestType。

Also update your html to post an array with all the request type ids. 同时更新您的html以发布具有所有请求类型ID的数组。 Next sync all the types with the images. 接下来,将所有类型与图像同步。

@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM