laravel - 迁移中的默认值 0 忽略请求值 laravel
问题描述
我有桌子(产品)
Products 表有三列( id 、 product_name 、 product_quantity )
如果输入为空,我希望 product_quantity 列默认设置值为 0
这是迁移代码:
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_name');
$table->integer('product_quantity')->default('0');
$table->timestamps();
});
}
这是 ProductsController 代码:
public function store(Request $request)
{
$rules = [
'product_name' => 'required',
// 'product_quantity' => 'nullable',
];
$customMessages = [
'product_name.required' => 'please insert product name ',
];
Product::create($this->validate($request, $rules, $customMessages));
return back();
}
和这个产品型号代码:
Protected $fillable = ['product_name' ,'product_quantity'];
但是当我存储具有任何值的请求时,它会忽略该值并保存默认值(0)
解决方案
首先,您必须注意在迁移default()
方法中设置的值。如果您使用的是integer
类型,则传入 a 是不正确string
的default()
:
$table->integer('product_quantity')->default(0); // turn the '0' into 0
另一个观察是$this->validate()
方法只返回一个经过验证的数据数组,所以如果你已经评论了验证规则 product_quantity
,它永远不会被传递给Product::create()
。话虽如此,数据库没有收到product_quantity
价值,所以它设置为默认值(0)。
如果您想product_quantity
被传递给Product::create()
您必须取消注释该值的规则。
我希望这个解释对你有所帮助。
推荐阅读
- r - 在数字和 NA 列表中获取元素权重
- cluster-analysis - 如何在 Sklearn 中使用带有混合(分类和数字)数据的 silhouette_score?
- asp.net-mvc - (MVC) 我的共享 _Layout 中有一个搜索栏。它适用于其他视图,但不适用于 _Layout
- php - return redirect('/') 和 Redirect::to('/')->send() 有什么区别?laravel 中的函数
- snowflake-cloud-data-platform - 用于雪花的 Kafka 连接器不断失败
- node.js - 错误 node_modules/jest-diff/build/diffLines.d.ts(8,13): 错误 TS1005: '=' 预期。在嵌套js中
- amazon-web-services - 如何通过 AutoScaling 动态增加 AWS EMR 上的 ulimit?
- clone - 乐克隆物体没有沉没
- django - 如何在 Django 中以编程方式将用户添加到组
- javascript - 我希望选择 HTML 表格单元格并在屏幕上可见