如何在laravel中的第3个表中保存子属性

时间:2017-10-23 05:52:41

标签: php mysql laravel

我想将sub-attribute数据保存在3rd表中,但我发现Call to undefined method App\Product::mores()错误。

逻辑:

获取product_id +获取submore_id将其保存到product_mores表。

问题:

问题在于我不想获得more_id,而是希望获得submore_id

层级

  1. 更多= CPU
  2. Submore = Core i7
  3. Product_id = 67
  4. 结果将如下:

    enter image description here

    通常情况下,我应该保存属性ID,这样很容易:

    $product->mores()->sync($request->mores, false);
    

    保存产品后,我需要提供submore ID我收到错误,并说:

    Call to undefined method App\Product::mores()
    

    引导我:

    $product->mores()->sync($request->mores, false);
    

    创建方法:

    public function create()
        {
          $categories = Category::all();
          $subcategories = Subcategory::all();
          $submores = Submore::all();
          $user = Auth::user();
          $brands = Brand::all();
          return view('admin.products.create', compact('user', 'categories', 'subcategories', 'submores', 'brands'));
        }
    

    存储方式:

    //......
          $product->save();
          $product->mores()->sync($request->mores, false);
    
          //Display a successful message upon save
          Session::flash('flash_message', 'Product, '. $product->title.' created');
          return redirect()->route('products.index');
    

    创建刀片页面:

      <label for="mores">Attributes</label>
      <select class="tagsselector form-control" name="mores[]" multiple="multiple">
      <option>Select Attribute</option>
        @foreach($submores as $more)
           <option value="{{ $more->id }}">{{ $more->title }}</option>
        @endforeach
      </select>
    

    有什么想法吗?

1 个答案:

答案 0 :(得分:0)

解决

我需要的只是在我的模型函数中添加表名和列名,如下所示:

public function submores()
  {
     return $this->belongsToMany(Submore::class, 'product_mores', 'product_id', 'submore_id');
  }

并且还将保存功能从mores更改为submores,如下所示:

$product->submores()->sync($request->submores, false);

然后将表单中的namefor更改为submores

<label for="submores">Attributes</label>
<select class="tagsselector form-control" name="submores[]" multiple="multiple">
//// rest of the code...