Laravel - 使用其他值/复选框数组更新数据透视表

时间:2017-11-14 10:49:33

标签: php laravel checkbox pivot

我有一个表单,列出可以添加到购物清单的产品,以及每个产品的可选文本字段说明。复选框用于选择将哪些产品添加到购物清单。

我遇到的问题是必须勾选第一个产品复选框,以便将后续产品中的注释插入到product_shopping_list数据透视表中。

控制器

public function update($shoppingList)
{
    // Check if any product checkboxes ticked
    if (request('products'))
    {
        // Get products (array)
        $products = request('products');
        // Get notes (array)
        $notes = request('notes');
        // Get shopping list
        $shoppingList = ShoppingList::find($shoppingList);
        // Save (attach products to shopping list and notes)
        $sync_data = [];
        for ($i = 0; $i < count($products); $i++)
        {
            $sync_data[$products[$i]] = ['notes' => $notes[$i]];
        }
        $shoppingList->products()->attach($sync_data);
        // Message
        session()->flash(
            'message', 'Your products have been added to your list.'
        );
    } else {
        // If no checkboxes ticked
        session()->flash(
            'message', 'No products selected.'
        );
    }
    // Redirect
    return redirect()->route('shopping-list.show', $shoppingList);
}

查看

@forelse ($products as $product)
    <div class="checkbox">
        <label for="products">
        {!! Form::checkbox('products[]', $product->id, false) !!}
        @if ($product->essential)
            <span class="essential">{{ $product->title }}</span>
        @else
            {{ $product->title }}
        @endif
        </label>
    </div>
    <div class="form-group">
        {!! Form::label('notes', 'Note') !!}
        {!! Form::text('notes[]', null, [
            'class' => 'form-control',
            'placeholder' => 'Note'
        ]) !!}
    </div>

@empty
    <div class="alert alert-info" role="alert">
        There are no available products.
    </div>
@endforelse

数据透视表架构

Schema::create('product_shopping_list', function (Blueprint $table) {
    $table->unsignedInteger('product_id');
    $table->unsignedInteger('shopping_list_id');
    $table->string('notes')->nullable();
    $table->primary(['product_id', 'shopping_list_id']);
    $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
    $table->foreign('shopping_list_id')->references('id')->on('shopping_lists')->onDelete('cascade');
});

1 个答案:

答案 0 :(得分:0)

我想我已经解决了这个问题。 以下是对视图的更改:

{!! Form::text('notes[' . $product->id . ']', null, [
    'class' => 'form-control',
    'placeholder' => 'Note'
]) !!}

对控制器的更改:

// Save (attach products and notes to shopping list)
foreach ($products as $id)
{
    $shoppingList->products()->attach($shoppingList->id,
    ['product_id' => $id, 'notes' => $notes[$id]]);
}