Laravel implementing belongsTo one product for one

2019-08-27 18:10发布

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 model:

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

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

productCategories model:

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

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

and store function into 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'));
}

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

UPDATE

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))

migration files:

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();
    });
}

1条回答
Root(大扎)
2楼-- · 2019-08-27 18:41

From your question and comments, I understand the following.

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.

Migrations:

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');
    });
}

Models

products model:

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 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');
    }
}

Controller

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'));
}

Hope it will helps..

查看更多
登录 后发表回答