什么是“批量分配"?在 Laravel 中是什么意思?

2021-12-26 00:00:00 php laravel eloquent mass-assignment

当我浏览有关 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();

相关文章