【问题标题】:Laravel migration default value for integer not working整数的 Laravel 迁移默认值不起作用
【发布时间】:2020-09-07 00:45:10
【问题描述】:

我正在使用 laravel 版本 6 和数据库 postgresql。 所以我尝试将列max_quantity 添加到现有表products,默认值设置为2147483647

Schema::table('products', function (Blueprint $table) {
    $table->integer('max_quantity')->default(2147483647);
});

控制器

public function store(CreateProduct $request)
{
   $validated = $request->validated();
   Product::create($validated);
}

这里的 max_quantity 看起来像在 postgres 中

当我尝试创建产品时,错误提示

SQLSTATE[23502]:非空违规:7 错误:列中的空值 "max_quantity" 违反非空约束

我该如何解决这个问题?

【问题讨论】:

  • 看起来您正在尝试向该字段插入空值,您能向我们展示您创建的产品代码吗?
  • @catcon 是的,我没有注意到 :)。如果 max_quantity 设置为 null,我将删除它。

标签: laravel


【解决方案1】:

你出错的原因

SQLSTATE[23502]:非空违规:7 错误:列中的空值 "max_quantity" 违反非空约束

因为当您创建产品时,您包含了 max_quantity 和值 null 要解决您的问题,如果值为null,则不要包含max_quantity

例如:

if ($request->max_quantity == null) {
   unset($request->max_quantity);
}

Product::create($request->only([...]))

这样当产品创建时max_quantity设置为2147483647

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-06
    • 2021-12-10
    • 2019-07-18
    • 2020-04-20
    • 2018-11-23
    • 2016-08-28
    • 1970-01-01
    • 2017-06-18
    相关资源
    最近更新 更多