php 如何使用laravel存储数组数据?

a64a0gku  于 2023-10-15  发布在  PHP
关注(0)|答案(1)|浏览(174)

我试图存储另一个表的数据,但它不工作。我是新的laravel。
请帮帮我,伙计们。
我有一个名为external_event_venue的表,其中我有一个名为amenities的列。
我有另一个名为venue_amenities的表,其中我将id作为外键external_event_venue_id,列名为amenity_id。

我分配表之间的关系是这样的:ExternalEventVenue.php

public function amenities()
 {
     return $this->hasMany(VenueAmenities::class,'external_event_venue_id', 'id');
 }

我已经为animities创建了.blade文件:

<x-forms.label fieldId="amenity" :fieldLabel="__('modules.venue.amenities')"      fieldName="amenities[]" fieldRequired="true">
</x-forms.label>
<div class="d-flex flex-wrap mb-3 ">
       @foreach(config('global.amenities') as $key => $value)
           <x-forms.checkbox :fieldLabel="$value" fieldName="amenities[]" fieldId="{{$key}}" fieldValue="{{$key}}"/>
       @endforeach
</div>

我在global.php文件中为它分配了数组:

<?php
    return[
          'amenities'  => [1 => 'Beachfront', 2 => 'A/V Equipement', 3 => 'Handicap Accessible', 4     => 'Pet Friendly', 5 => 'Outdoor Space', 6 => 'Breakout rooms', 7 => 'Business Center', 8 => 'Cab', 9 => 'Rooftop',10 => 'Theater space' ,11 => 'Parking' ,12 => 'Media room',13 => 'Spa' ,14 => 'WiFi'],
];

我想使用控制器方法存储数组数据:

public function store(Request $request)
    {
           ...
           $venue->amenities = $request->amenity;
           $venue->save();
           $venue = new ExternalEventVenue();
            if (isset($request->amenity_id)) {
            foreach ($request->amenity_id as $amenityId) 
            {
                if ($amenityId !== null) {
                    $amenity = new VenueAmenities();                    
                    $amenity->amenity_id = $amenityId;
                    $amenity->external_event_venue_id = $venue->id;
                    $amenity->save();
                }
            }
        }
    }

请任何人都可以帮助我这个...

dxxyhpgq

dxxyhpgq1#

让我们从一个简化的数据库开始,以实现您的目标。
让我们假设我们有这个模式:

venues
    id
    name
    
amenities
    id
    name

amenity_venue (pivot table)
    id
    venue_id
    amenity_id

Venue模型:

class Venue extends Model
{
    public function amenity()
    {
        return $this->belongsToMany(Amenity::class);
    }
}

Amenity模型:

class Amenity extends Model
{
    // ...
}

神奇的是sync函数,它将多对多关系的数据存储在pivot表(amenity_venue)中。

public function store(Request $request)
{
    //...

    // if you don't create a new entity here, you have to pass the ID of an existing entity
    $venue = Venue::find($request->venueId);

    // amenities[] are the selected checkboxes as an array
    $venue->amenity()->sync($request->amenities);
}

如果你遵循命名约定,Laravel将为你做所有的工作。

相关问题