Laravel 模型中有太多可填写的字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40956854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Too many fillable fields in model Laravel?
提问by Griboedov
I have around 200 fields in a table that are numbered:
我在一个表中有大约 200 个字段被编号:
field_1
field_2
etc
I tried to insert data in table:
我试图在表中插入数据:
Result::insert($data);
Where $data
is multiple array:
$data
多数组在哪里:
$data = [] = array("field_1" => 3);
$data = [] = array("field_1" => 2);
Can I set *
in option protected $fillable = ["*"];
to make all fields fillable?
我可以设置*
选项protected $fillable = ["*"];
使所有字段都可填写吗?
回答by Alexey Mezenin
If you need to set all columns as fillable, do this in the model:
如果您需要将所有列设置为可填充,请在模型中执行此操作:
protected $guarded = [];
If you would like to make all attributes mass assignable, you may define the $guarded property as an empty array
如果你想让所有的属性都可以大量赋值,你可以将 $guarded 属性定义为一个空数组
回答by Mahfuzul Alam
In such scenario, you can try doing the reverse. For example: id
, created_at
and updated_at
field as $guarded. Like:
在这种情况下,您可以尝试反向操作。例如:id
,created_at
和updated_at
$guarded 字段。喜欢:
protected $guarded = ['id', 'created_at', 'updated_at'];
Except these rest will be considered as fillable
i.e. mass assignable.
除了这些以外其余部分将被视为fillable
即质量分配。
You can find details in Official Laravel Doc
您可以在Laravel 官方文档中找到详细信息
Guarding Attributes
While $fillableserves as a "white list" of attributes that should be mass assignable, you may also choose to use $guarded. The $guardedproperty should contain an array of attributes that you do not want to be mass assignable. All other attributes not in the array will be mass assignable. So, $guardedfunctions like a "black list". Of course, you should use either $fillableor $guarded- not both.
守护属性
虽然$fillable用作应该可以批量分配的属性的“白名单”,但您也可以选择使用$guarded。在$把守属性应包含的属性的数组,你不希望成为质量分配。不在数组中的所有其他属性都可以批量分配。所以, $guarded 的功能就像一个“黑名单”。当然,您应该使用$fillable或$guarded- 不能同时使用。