程序开发中经常涉及到金额和日期的转换
1 日期在数据库中存储为timestamp类型,前端vue+element显示时使用Unix时间戳(Unix timestamp)*1000,单位毫秒
原理: get到api时 转为时间戳INT * 1000, set到数据库时 将int/1000 转为日期
2 金额字段,数据库类型为int类型单位分,前端转换为元显示
原理: get到API时/100, set到数据库时*100
参考自 hao-li/laravel-amount
一 首先laravel中新建Trait AmountAndDateTrait
<?php
namespace App\Ship\Parents\Models;
/**
* Class AmountAndDateTrait
*
* 金额自动转换
* get到API时/100,
* set到数据库时*100
*
* 系统中涉及到金额的字段,View 层表现的时候一般都是以元为单位使用小数形式展示,
* 不过 Domain 层存储时从空间、性能、容错角度出发,
* 经常以分为单位,用整型来存储。
*
* 原理
* 将转换逻辑封装在 AmountTrait 中,
* 覆写 Model 类的 getMutatedAttributes, mutateAttributeForArray, getAttributeValue 及 setAttribute 方法,
* 当访问相关字段时自动进行转换处理。
*
*
*
* 日期自动转换
* get到api时 转为时间戳INT * 1000
* set到数据库时 将int/1000 转为日期
*
*
*
*
*
*
*
*
*
*/
Trait AmountAndDateTrait
{
public functi