Laravel实现属于一个或某个类别的一种产品 [英] Laravel implementing belongsTo one product for one or some category

查看:82
本文介绍了Laravel实现属于一个或某个类别的一种产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有product_categoryproducts,一个product可能属于product_category表中的一个或某个类别,现在我的问题是:当用户提交具有一个或某个类别的产品时,如何我将其保存在数据库中,以使某个类别拥有一种或某些产品?

in my database i have product_category and products that one product maybe belongs to one or some category in product_category table, now my question is: when user on submitting product with one or some category how can i save that on database to have for example one category have one or some product?

在视图中,我有多个选择:

in view i have multiple select as:

{{ Form::select('categories[]', $productCategories, null, array('class' => 'multiselect-success multiselect_selected','multiple'=>'multiple')) }} 

products型号:

class Products extends Model
{
    protected $table = 'products';
    protected $guarded = ['id'];
    protected $casts = [
        'images' => 'array'
    ];

    public function productCategories()
    {
        return $this->belongsTo(ProductCategories::class);
    }
}

productCategories型号:

class ProductCategories extends Model
{
    protected $table = 'product_categories';
    protected $guarded =['id'];
    protected $casts=[
        'images'=>'array'
    ];

    public function products()
    {
        return $this->hasMany(Products::class);
    }
}

store转换为controller:

public function store(RequestProducts $request)
{
    try {
        $data = Products::create([
            'name' => $request->name,
            'amount' => $request->amount,
            'product_code' => $request->product_code,
            'weight' => $request->weight
            /* MY PROBLEM IS HERE */
            'category_id' => $request->categories
        ]);
    } catch (Exception $ex) {
        ...
    }

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

html视图中的

categories是一个数组,我该如何实现呢?

in html view categories is an array and how can i implementing that?

更新

使用createMany更新代码后,出现此错误:

after update code with createMany i get this error:

General error: 1364 Field 'category_id' doesn't have a default value (SQL: insert into `products` (`name`, `lang`, `amount`, `product_code`, `weight`, `images`, `updated_at`, `created_at`) values (eqweqwe, fa, 45,000, asd, asdasd, '', 2017-12-09 04:45:44, 2017-12-09 04:45:44))

迁移文件:

public function up()
{
    Schema::create('product_categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('category_name');
        $table->string('lang', 2);
        $table->text('images');
        $table->timestamps();
    });
}

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('amount');
        $table->string('product_code');
        $table->string('weight');
        $table->string('lang', 2);
        $table->text('images');
        $table->integer('category_id')->unsigned()->index();
        $table->foreign('category_id')->references('id')->on('product_categories')->onDelete('cascade');
        $table->timestamps();
    });
}

推荐答案

从您的问题和评论中,我理解以下内容.

From your question and comments, I understand the following.

许多产品可能具有类别"category_1",而"product_1"可能属于许多类别.

Many products may have the category "category_1" and "product_1" may belongs to many categories.

要实现此目的,您必须使用多对多"关系. 我已经更新了您的代码,这可能会对您有所帮助.

To implement this you have to use "Many To Many" relationship. I have updated your code, this might help you.

迁移:

public function up()
{
    Schema::create('product_categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('category_name');
        $table->string('lang', 2);
        $table->text('images');
        $table->timestamps();
    });
}

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('amount');
        $table->string('product_code');
        $table->string('weight');
        $table->string('lang', 2);
        $table->text('images');
        $table->timestamps();
    });
}
    public function up()
{
    Schema::create('products_product_category', function (Blueprint $table) {
        $table->integer('product_id');
        $table->integer('product_category_id');
    });
}

模型

产品型号:

class Products extends Model
{
    protected $table = 'products';
    protected $guarded = ['id'];
    protected $casts = [
        'images' => 'array'
    ];

    public function productCategories()
    {
        return $this->belongsToMany(ProductCategories::class,'products_product_category');
    }
}

productCategories模型:

productCategories model:

class ProductCategories extends Model
{
    protected $table = 'product_categories';
    protected $guarded =['id'];
    protected $casts=[
        'images'=>'array'
    ];

    public function products()
    {
        return $this->belongsToMany(Products::class, 'products_product_category');
    }
}

控制器

public function store(RequestProducts $request)
{
    try {
        $data = Products::create([
            'name' => $request->name,
            'amount' => $request->amount,
            'product_code' => $request->product_code,
            'weight' => $request->weight
        ]);
        $data->productCategories()->sync($request->categories);
    } catch (Exception $ex) {
        ...
    }

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

希望这会有所帮助.

这篇关于Laravel实现属于一个或某个类别的一种产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆