简体   繁体   中英

Laravel 5.4 store Many to Many relationship in database

I have 2 models

  • ImageRequest
  • RequestType

1 ImageRequest can have Many RequestTypes and 1 RequestType can have Many ImageRequests.

I translated this like this in my models:

ImageRequest Model:

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

RequestType Model:

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

My migration for the image_requests table:

$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:

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

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. It can't store all request_type_id's.

How can I store multiple request_type_id's?

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.

Also update your html to post an array with all the request type ids. 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'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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