在 Laravel 中更改模型中的字段/属性值

16

我有一个名为products的表,其中包含一个price列。在模型中,我想做这样的事情:

public function getPriceAttribute()
{
    return number_format($this->price);
}

所以在我的视野中使用

{{ $property->price }} €

如何从数据库中获取值200而不是200.00这种带有小数的值?

这种情况可以实现吗?


1
为什么你不能只是使用(float)$property->price? - Jilson Thomas
必须有一种方法从模型中实现,而不是仅为此创建一个新的帮助程序... - Sebastian Corneliu Vîrlan
是的,您可以从模型中进行这个操作。它被称为Eloquent属性转换。您尝试过了吗? - Jilson Thomas
你需要在 number_format 函数调用中添加 decimals 参数:return number_format($this->price, 2); - Fiete
不必要,是可选的。 - Sebastian Corneliu Vîrlan
显示剩余2条评论
2个回答

27

这是解决我的问题的方法:

public function getPriceAttribute()
{
    return number_format($this->attributes['price']);
}

这将覆盖$property->price的值(根据注释)


这会不会使 $property->price 过载? - Laerte
1
@Laerte,为了澄清,是的,这将会。 - Script47
1
@Laerte 这就是为什么仅仅为了格式化而使用它并不是一个好主意。一个全局的帮助类会是一个好主意,或者如果你更喜欢访问器,那么自定义访问器也是很棒的选择。比如 pubf getFormattedPriceAttribute() 和 $property->formatted_price。 - gramgram

4
您可以通过将原始值作为参数传递来实现,例如:

您可以通过将原始值作为参数传递来实现,就像这样:

public function getPriceAttribute($price)
{
   return number_format($price);
}

您可以在此处了解更多有关 Mutators(和 Casting)的信息: https://laravel.com/docs/8.x/eloquent-mutators

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接