【问题标题】:General error: 1364 Field 'products_id' doesn't have a default value一般错误:1364 字段“products_id”没有默认值
【发布时间】:2020-07-23 06:21:33
【问题描述】:

你好,我有两张桌子:

产品:

 public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            $table->string('title');
            ...
            $table->boolean('slider_mode')->default(false);
        });
    }

和滑块:

public function up()
    {
        Schema::create('slider', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            ...
            $table->integer('products_id')->unsigned()->index();
            $table->foreign('products_id')->references('id')->on('products')->onDelete('cascade');
        });

问题是当我使用滑块创建产品表时,产品的 id 没有在 products_id 中引用

这是我的控制器(存储功能):

...
 if($x1['slider_mode'] == 1){      # x1 is $request->all();
            Slider::create($x1);
        }
        Product::create($x1);


        return redirect('admin/products');

当我创建两者时,products_id 是否应该不使用产品 ID 自动完成?

但我遇到了错误:

一般错误:1364 字段“products_id”没有默认值

【问题讨论】:

  • 为什么不简单地将 product_id 设为 nullable ,如果你不存储它会创建滑块

标签: laravel migration


【解决方案1】:

如果您在模型内部设置关系, 你可以这样做:

$product = Product::create($x);
$product->sliders()->create($x);

新创建的滑块将自动拥有product_id 的产品。

你可以阅读更多here我认为这就是你所需要的。

【讨论】:

    【解决方案2】:

    product_id 是自动递增的,但对于 products 表而不是 slider 表。

    如果要在没有product_id 的情况下插入slider 表,则必须更新products 表迁移并将值设置为可为空:

    $table->integer('products_id')->unsigned()->index()->nullable();
    

    或者如果你想要product_id,你也应该设置product_id

    【讨论】:

      猜你喜欢
      • 2019-11-23
      • 2021-02-28
      • 2021-10-13
      • 2017-03-02
      • 2020-02-03
      • 2020-02-27
      • 2016-06-13
      • 2021-01-18
      • 2021-07-30
      相关资源
      最近更新 更多