简体   繁体   English

Laravel 如何将一个产品插入多个类别

[英]Laravel how to insert one product to many categories

I tried but it duplicated products, I wish to save one product under many category for one product_id.我试过了,但它重复了产品,我希望为一个 product_id 保存一个产品在多个类别下。 Here my View Create (Product)在这里我的视图创建(产品)

<div class="form-group row" id="category">
                        <label class="col-md-3 col-from-label">{{translate('Category')}} <span class="text-danger">*</span></label>
                        <div class="col-md-8">
                            <select class="form-control ml-selectpicker" name="category_id" id="category_id" data-live-search="true" required>
                                @foreach ($categories as $category)
                                <option value="{{ $category->id }}">{{ $category->getTranslation('name') }}</option>
                                @foreach ($category->childrenCategories as $childCategory)
                                @include('categories.child_category', ['child_category' => $childCategory])
                                @endforeach
                                @endforeach
                            </select>
                        </div>
                    </div>

And Here My control ( Create product )在这里我的控制(创建产品)

   /**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
    $categories = Category::where('parent_id', 0)
        ->where('digital', 0)
        ->with('childrenCategories')
        ->get();

    return view('backend.product.products.create', compact('categories'));
}

And for save为了保存

$product->category_id = $request->category_id;

Here My model:这是我的 model:

 public function category()
{
    return $this->belongsTo(Category::class);
}

I believe that there function like $product->Categories()->sync([1, 3, 4]);我相信有 function 之类的 $product->Categories()->sync([1, 3, 4]);

if You want to store a product under many categories then.如果您想将产品存储在许多类别下。 You have to change Your Relationship to Many-to-many(a products can have many categories and a categories have many products).您必须将您的关系更改为多对多(一个产品可以有很多类别,一个类别可以有很多产品)。 So You have to create Three Tables所以你必须创建三个表

  1. Products- to store products产品- 存储产品
  2. categories- to store categories类别 - 存储类别
  3. category_products- pivot table category_products- pivot表

Then Your Models Will be Like below Products Model那么您的型号将如下所示产品 Model

 public function categories(){
     return $this->belongsToMany(Category::class);
}

Category Model类别 Model

public function products(){
     return $this->belongsToMany(Product::class);
}

Then You can Simply use the function sync() to store a products under many categories Many to many relationships in laravel然后您可以简单地使用 function sync()来存储多个类别下的产品laravel 中的多对多关系

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM