Laravel 9 修改器报错方法未定义
1. 运行环境
1). 当前使用的 Laravel 版本?
Laravel 9.x
2). 当前使用的 php/php-fpm 版本?
PHP 版本:8.0
3). 当前系统
Centos 7
4). 业务环境
数据库中的价格以 分
为单位存整形,所以定义了价格的访问器和修改器
2. 问题描述?
代码如下
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
...
protected function price(): Attribute
{
return Attribute::make(
get: fn($value) => (float)bcdiv(number_format($value), 100, 2),
set: fn($value) => (int)bcmul(number_format($value, 2), 100)
);
}
}
访问器是正常的,假设数据库中的价格为
100(分)
,取出来的值为1
修改器无法使用,通过浏览器更新数据的时候会报错
Call to undefined method App\Models\Product::price()
通过 tinker 调试发现,修改器在 tinker 中可用
去掉修改器,更新依然报错
Call to undefined method App\Models\Product::price()
,只有访问器修改器都去掉才正常
通过老版本的方法定义修改/访问器
public function getPriceAttribute($price)
{
return (float)bcdiv(number_format($price), 100, 2);
}
public function setPriceAttribute($price)
{
return (int)bcmul(number_format($price, 2), 100);
}
访问器正常,但是同时更新标题和价格,标题可以更新,价格没变
number_format(12345.67, 2) 会带千位号的。
批量更新不能用修改器吧