【问题标题】:Laravel implementing belongsTo one product for one or some categoryLaravel 实现属于一个或某个类别的一个产品
【发布时间】:2017-12-08 15:19:35
【问题描述】:

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

在视图中我有多个选择:

{{ 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 是一个数组,我该如何实现它?

更新

使用createMany 更新代码后,我收到此错误:

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

【问题讨论】:

  • 在我看来,您需要在产品和具有中间表的类别之间建立多对多关系。
  • @ab_in 我对多对多没有任何问题,但我认为实现是一对多
  • 那么您成功创建了产品,现在您需要创建类别并将其附加到您的新产品中吗?
  • 是的。将一篇帖子附加到一个或某些类别

标签: php laravel laravel-5 eloquent


【解决方案1】:

从你的问题和cmets,我理解以下内容。

许多产品可能有类别“category_1”,而“product_1”可能属于许多类别。

要实现这一点,您必须使用“多对多”关系。 我已经更新了你的代码,这可能会对你有所帮助。

迁移:

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 型号:

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

希望它会有所帮助..

【讨论】:

  • 看来你是对的。请让我检查一下
  • products_product_category 文件的外键在哪里?
  • laravel 自动分配外键约束..$table->integer('product_id');//foriegnkey for product table $table->integer('product_category_id'); // foriegnkey for product_categories table
  • 请参阅 laravel.com/docs/5.5/eloquent-relationships#many-to-many 了解更多信息。
猜你喜欢
  • 2016-09-02
  • 2011-08-25
  • 2016-10-16
  • 1970-01-01
  • 2018-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多