What does quot;Mass Assignmentquot; mean in Laravel?(什么是“批量分配?在 Laravel 中是什么意思?)
问题描述
当我浏览有关 Eloquent ORM 主题部分的 Laravel 文档时,我得到了一个新术语批量分配".
When I went through Laravel Document about Eloquent ORM topic part, I got a new term "Mass Assignment".
文档显示如何进行批量分配和 $fillable
或 $guarded
属性设置.但是经历了那之后,我对批量分配"并没有清楚的了解.以及它是如何工作的.
Document show How to do Mass Assignment and the $fillable
or $guarded
properties settings. But after went through that, I didn't have a clearly understand about "Mass Assignment" and how it works.
在我过去使用 CodeIgniter 的经验中,我也没有听说过这个术语.
In my past experience in CodeIgniter, I also didn't hear about this term.
有人对此有一个简单的解释吗?
Does anyone have a simple explanation about that?
推荐答案
Mass assignment 是当你发送一个数组到模型创建时,基本上是一次性在模型上设置一堆字段,而不是一个一个,类似:
Mass assignment is when you send an array to the model creation, basically setting a bunch of fields on the model in a single go, rather than one by one, something like:
$user = new User(request()->all());
(这不是分别在模型上显式设置每个值.)
(This is instead of explicitly setting each value on the model separately.)
您可以使用 fillable
来保护您希望它实际允许更新的字段.
You can use fillable
to protect which fields you want this to actually allow for updating.
您还可以通过执行以下操作阻止所有字段可批量分配:
You can also block all fields from being mass-assignable by doing this:
protected $guarded = ['*'];
假设在您的用户表中有一个字段是 user_type
并且可以具有 user/admin 的值
Let's say in your user table you have a field that is user_type
and that can have values of user / admin
显然,您不希望用户能够更新此值.理论上,如果您使用上述代码,有人可以将 user_type
的新字段注入表单并将admin"与其他表单数据一起发送,然后轻松地将他们的帐户切换到管理员帐户... 坏消息.
Obviously, you don't want users to be able to update this value. In theory, if you used the above code, someone could inject into a form a new field for user_type
and send 'admin' along with the other form data, and easily switch their account to an admin account... bad news.
通过添加:
$fillable = ['name', 'password', 'email'];
您确保只有那些值可以使用 mass assignment
You are ensuring that only those values can be updated using mass assignment
为了能够更新 user_type
值,您需要在模型上显式设置并保存它,如下所示:
To be able to update the user_type
value, you need to explicitly set it on the model and save it, like this:
$user->user_type = 'admin';
$user->save();
这篇关于什么是“批量分配"?在 Laravel 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么是“批量分配"?在 Laravel 中是什么意思?
基础教程推荐
- HTTP 与 FTP 上传 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01