appel / 货币属性
此包已被弃用且不再维护。未建议替代包。
在您的 Eloquent 模型中使用基于美元的值并将其存储为整数。
v1.1.0
2019-09-19 16:45 UTC
Requires
- php: ^7.1
- illuminate/database: ^5|^6
Requires (Dev)
- phpunit/phpunit: ^8.0
README
注意:此仓库已被弃用,建议使用 Laravel 7 中引入的 Eloquent 自定义转换,以替代它。
您可以使用以下 Cast 类使用 Eloquent 自定义转换来复现此包的功能
<?php namespace App\Casts; use Illuminate\Contracts\Database\Eloquent\CastsAttributes; class Currency implements CastsAttributes { /** * Cast the given value into currency format. * * @param \Illuminate\Database\Eloquent\Model $model * @param string $key * @param mixed $value * @param array $attributes * @return string */ public function get($model, string $key, $value, array $attributes) { return number_format((int) $value / 100, 2, '.', ''); } /** * Cast the given value back into an integer for storage. * * @param \Illuminate\Database\Eloquent\Model $model * @param string $key * @param mixed $value * @param array $attributes * @return int */ public function set($model, string $key, $value, array $attributes) { return (int) round((float) $value * 100); } }
货币属性
货币属性 是一个用于 Laravel / Eloquent 的包,当您需要存储货币单位且不想处理将货币存储在浮点/双精度格式时带来的所有复杂性。
使用此包,您将把货币字段存储为分(没有小数点),在检索时转换为美元,在存储时转换回分。
安装
通过 composer 安装此包
composer require appel/monetary-attributes
用法
在创建 Eloquent 模型时,不要扩展标准的 Laravel 模型类,而是扩展此包提供的模型类
<?php namespace App; use Appel\MonetaryAttributes\Model; class Product extends Model { // }
在您的 Eloquent 模型内部,在 $moneyAttributes
属性中定义模型的货币属性。
... class Product extends Model { protected $moneyAttributes = ['price','sale_price']; } ...
待办事项
- 改为使用特质而不是继承