Laravel 中访问器的正确使用

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

Proper Use of Accessors in Laravel

laraveleloquentaccessor

提问by Kelly Kiernan

I am new to Laravel and am building a simple CRUD app to learn more about the framework. I am curious about the proper use of accessors.

我是 Laravel 的新手,正在构建一个简单的 CRUD 应用程序以了解有关该框架的更多信息。我很好奇访问器的正确使用。

I thought accessors would be great for formatting a model's properties for display in a view, much like a filter in Angular. Currently I have a few accessors set to convert char(1) fields to full values in the view, like "c" to cash or "f" to financed. Is this the intended (or an acceptable) use of accessors? If so, what is a good way to prevent accessors from formatting properties that are binded to a form, for instance, in the edit route.

我认为访问器非常适合格式化模型的属性以在视图中显示,就像 Angular 中的过滤器一样。目前,我有一些访问器设置为将 char(1) 字段转换为视图中的完整值,例如“c”到现金或“f”到融资。这是访问器的预期(或可接受的)用途吗?如果是这样,什么是防止访问者格式化绑定到表单的属性的好方法,例如,在编辑路由中。

For example, I am storing a monetary amount in the db as a decimal but formatting it with characters ($150,00) for display in the show route. How can I prevent the accessor from altering the value when populating the edit form? (Validation will fail as the input is limited to numeric values).

例如,我在 db 中以十进制形式存储了一个货币金额,但将其格式化为字符($150,00)以在表演路线中显示。在填充编辑表单时,如何防止访问器更改值?(验证将失败,因为输入仅限于数值)。

http://laravel.com/docs/4.2/eloquent#accessors-and-mutators

http://laravel.com/docs/4.2/eloquent#accessors-and-mutators

http://laravel.com/docs/4.2/html#form-model-binding

http://laravel.com/docs/4.2/html#form-model-binding

回答by Marcin Nabia?ek

Everything depends on your needs. The key is that you don't need to create accessors to actual columns/properties. For example let's assuyme in DB you have price field.

一切都取决于您的需求。关键是您不需要为实际的列/属性创建访问器。例如,让我们在 DB 中假设您有价格字段。

Using the following code:

使用以下代码:

$model = Model::find(1);
echo $model->price;

You can display row price just to display data from database.

您可以显示行价格只是为了显示数据库中的数据。

But you can also create accessor for unexisting property:

但是你也可以为不存在的属性创建访问器:

public function getCurPriceAttribute($value)
{
     return '$ '.($this->price * 1.08); // for example adding VAT tax + displaying currency
}

now you can use:

现在你可以使用:

$model = Model::find(1);
echo $model->price;
echo $model->cur_price;

Now if you want to put data into form you will use $model->priceto allow user to change it without currency and in other places where you want to display product value with currency you will use $model->cur_price

现在,如果您想将数据放入表单中,您将使用它$model->price来允许用户在没有货币的情况下更改它,并且在您想要使用货币显示产品价值的其他地方,您将使用$model->cur_price