迁移中的默认值0忽略请求值laravel



我有表格(产品(

产品表有三列(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();
});
}

这是产品控制器代码:

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类型,则在default():中传递string是不正确的

$table->integer('product_quantity')->default(0); // turn the '0' into 0

另一个观察结果是$this->validate()方法只返回一个已验证数据的数组,因此如果您对product_quantity的验证规则进行了注释,它将永远不会传递给Product::create()。也就是说,数据库没有接收到product_quantity值,所以它设置为默认值(0(。

如果要将product_quantity传递给Product::create(),则必须取消注释该值的规则。

我希望这个解释对你有帮助。

最新更新