将值更新为具有多对多关系的数据库Laravel

时间:2017-08-21 03:05:43

标签: php database synchronization many-to-many laravel-5.3

我想将值数据从单选按钮更新到数据库表product_categories,但我感到困惑。因为我的数据属于很多。

这里我属于产品型号中的许多功能



public function categories()
    {
        return $this->belongsToMany(Category::class,'products_categories','product_id','category_id')
            ->withPivot('id')
            ->orderBy('category_id')
            ->withTimestamps();
    }




这是我在视图中的单选按钮结构



{!! Form::model($product, ['route' => ['products.update', $product->id], 'method' => 'patch']) !!}
<div class="dropdown dropdown-full-width dropdown-category">
  <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">
          <span class="name">
              <span id="category-select">Choose Category</span>
          </span>
          <span class="caret"></span>
      </button>
  <div class="dropdown-menu row">
    <div class="col-md-4">
      <li><strong>By {{ $category[1] }}</strong></li>
      @foreach($category1 as $occasions)
      <li>
        <div class="checkbox">
          <label><input type="radio" name="category['occasions']" class="category-radio" value="{{ $occasions->id }}"> {{ $occasions->name }}</label>
        </div>
      </li>
      @endforeach
    </div>
    
    <div class="col-md-4">
      <li><strong>By {{ $category[2] }}</strong></li>
      @foreach($category2 as $types)
      <li>
        <div class="checkbox">
          <label><input type="radio" name="category['types']" class="category-radio" value="{{ $types->id }}"> {{ $types->name }}</label>
        </div>
      </li>
      @endforeach
    </div>

    <div class="col-md-4">
      <li><strong>By {{ $category[3] }}</strong></li>
      @foreach($category3 as $flowers)
      <li>
        <div class="checkbox">
          <label><input type="radio" name="category['flowers']" class="category-radio" value="{{ $flowers->id }}"> {{ $flowers->name }}</label>
        </div>
      </li>
      @endforeach
    </div>
  </div>
</div>
{!! Form::close() !!}
&#13;
&#13;
&#13;

这里是我在控制器中的更新功能

&#13;
&#13;
public function update($id, UpdateProductRequest $request)
    {
        $product = $this->productRepository->findWithoutFail($id);

        $categories = Product::with('categories')->where('id','=', $product->id)->get();
        $idcategories = $categories[0]->categories;
        
        if (empty($product)) {
            Flash::error('Product not found');

            return redirect(route('products.index'));
        }

      //place update code for radio button here//

        Flash::success('Product updated successfully.');

        return redirect(route('products.index'));
    }
&#13;
&#13;
&#13;

我对与同步的多对多关系感到很困惑。

更新

这是product_categories

中的表格结构

enter image description here

0 个答案:

没有答案