Laravel Model::create 批量分配不适用于默认值为 null 的列
Laravel Model::create mass assignment not working for columns with null as default value
我的数据库中有一个 table,其中一些列可以为 null,当然默认值为 null。
在我的控制器中,我使用Model::create($request->all())
来保存。在保存数据时,可为空的列未填充任何值,仍然为空。
也许,在迁移过程中 ->nullable()
是个问题吗?
如果不是,有人可以解释为什么可以为 null 的列没有填充相应的值吗?我该如何解决这个问题?
看看Mass Assignment Documentation
So, to get started, you should define which model attributes you want to make mass assignable. You may do this using the $fillable property on the model
您必须将 $fillable
属性 添加到您的模型中,尤其是当您使用 Model::create($request->all())
.
时
public $fillable = [];
例如:
public $fillable = ['some_property', 'some_other'];
现在,如果您调用 create
方法,将分配 'some_property'
和 'some_other'
。
此外,您可以使用 $guarded
,它表示所有属性都是可分配的,没有任何内容受到保护
public $guarded= [];
Don't use $guarded
if you are going to create model by passing $request->all()
to create method
我的数据库中有一个 table,其中一些列可以为 null,当然默认值为 null。
在我的控制器中,我使用Model::create($request->all())
来保存。在保存数据时,可为空的列未填充任何值,仍然为空。
也许,在迁移过程中 ->nullable()
是个问题吗?
如果不是,有人可以解释为什么可以为 null 的列没有填充相应的值吗?我该如何解决这个问题?
看看Mass Assignment Documentation
So, to get started, you should define which model attributes you want to make mass assignable. You may do this using the $fillable property on the model
您必须将 $fillable
属性 添加到您的模型中,尤其是当您使用 Model::create($request->all())
.
public $fillable = [];
例如:
public $fillable = ['some_property', 'some_other'];
现在,如果您调用 create
方法,将分配 'some_property'
和 'some_other'
。
此外,您可以使用 $guarded
,它表示所有属性都是可分配的,没有任何内容受到保护
public $guarded= [];
Don't use
$guarded
if you are going to create model by passing$request->all()
to create method