php Model::unguard() 在 Laravel 5 的数据库种子文件中做了什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32795443/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:11:52  来源:igfitidea点击:

What does Model::unguard() do in the database seeder file from Laravel 5?

phplaravel-5

提问by Rohan

I am trying to find out what is the purpose of Model::unguard();and Model::reguard();in the DatabaseSeeder.phpfile that ships with Laravel. I have gone through the seeding documentation at laravel's site and googled but in vain.

我试图找出Laravel 附带的文件的目的Model::unguard();和内容。我已经浏览了 laravel 网站上的播种文档并用谷歌搜索但徒劳无功。Model::reguard();DatabaseSeeder.php

So what is the purpose of Model::unguard();? Assuming Model::reguard();is just the opposite.

那么目的是Model::unguard();什么?假设Model::reguard();正好相反。

回答by peaceman

Model::unguard()does temporarily disable the mass assignment protection of the model, so you can seed all model properties.

Model::unguard()暂时禁用模型的质量分配保护,因此您可以为所有模型属性设定种子。

Take a look at http://laravel.com/docs/5.1/eloquent#mass-assignmentfor more information about mass assignment in Eloquent.

查看http://laravel.com/docs/5.1/eloquent#mass-assignment了解有关 Eloquent 中批量分配的更多信息。

回答by Akongnwi Devert

Take for example the currency table Migration file

以货币表迁移文件为例

    $table->double('rate');
    $table->boolean('is_default')->default(false);

If your Currency Model file, the only fillables are

如果您的货币模型文件,唯一的可填写内容是

 protected $fillable = [
        'rate',
    ]

is_defaultcan never be set by mass assignment. For example

is_default永远不能通过批量赋值来设置。例如

Currency::create([
   'rate' => 5.6,
   'is_default' => true
])

will return a currency with

将返回一个货币

'rate' => 5.6
'is_default' => false

But you can mass assign the field using unguard and reguard as follows

但是您可以使用 unguard 和 reguard 批量分配字段,如下所示

Model::unguard()
Currency::create([
   'rate' => 5.6,
   'is_default' => true
])
Model::reguard()

Then your model will be created with

然后你的模型将被创建

'rate' => 5.6
'is_default' => true