Laravel:如何使用select2.js更新多个Select选项

时间:2018-07-02 21:09:34

标签: php html database laravel eloquent

我想更新我的数据库,但是它在选项字段中发送重复的值。

enter image description here

这是我的HTML代码:

<select name="size_id[]" multiple="multiple" style="margin-bottom:15px;"
        class="form-control select_multiple">
  @foreach($sizes as $skey=>$sitem)
        @foreach ($product->Sizes as $pkey=>$psize)
                <option value="{{$sitem->id }}"}} @if($sitem->id == $psize->id)selected="selected"@endif>
                    {{ $sitem->name}}+{{$skey}}
                </option>
        @endforeach
    @endforeach
</select>

产品型号:

 public function Sizes()
    {
        return $this->belongsToMany(Size::class,'product_sizes');
    }

尺寸型号:

public function Products()
{
    return $this->belongsToMany(Product::class, 'size_products','product_id','size_id');
}

1 个答案:

答案 0 :(得分:2)

您可以使用收藏集containsStrict来检查商品ID是否等于以下任何一种尺寸:

<select name="size_id[]" multiple="multiple" style="margin-bottom:15px;"
                                            class="form-control select_multiple">
@foreach($sizes as $skey=>$sitem)                                   
        <option value="{{$sitem->id }}"}} @if($product->Sizes->containsStrict('id', $item->id)) selected="selected" @endif>
        {{ $sitem->name }}+{{ $skey }}
    </option>
 @endforeach                                       
</select>