程序开发中经常涉及到金额和日期的转换
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 function __construct()
{
}
public static $amountTimes = 100;
/*Mutated是无引用时 原始调用 model时引用*/
public function getMutatedAttributes()
{
$attributes = parent::getMutatedAttributes();
if ($this->getAmountFields()) $attributes= array_merge($attributes, $this->getAmountFields());
if ($this->getDates()) $attributes= array_merge($attributes, $this->getDates());
//dump($attributes);
return $attributes;
}
protected function mutateAttributeForArray($key, $value)
{
/*dump($key);
dump($this->getDates());
dump($this->getAmountFields())*/;
if (in_array($key, $this->getAmountFields()) && is_int($value)) {
$return = $value / self::$amountTimes;
} else if (in_array($key, $this->getDates())) {
$return = is_int($value) ? $value * 1000 : strtotime($value) * 1000;
} else {
$return = parent::mutateAttributeForArray($key, $value);
}
return $return;
}
/*以下的是在transform中引用时 引用*/
//读取给API时
public function getAttributeValue($key)
{
// dump($this);
/* dump($key);
dump($this->getDates());
dump($this->getAmountFields());*/
$value = parent::getAttributeValue($key);
if (in_array($key, $this->getAmountFields()) && is_int($value)) {
$value = $value / self::$amountTimes;
} else if (in_array($key, $this->getDates())) {
// 数据库存的是 timestamp, 给前端的是int...
$value = is_int($value) ? $value * 1000 : strtotime($value) * 1000;
}
return $value;
}
//保存入数据库时设定
public function setAttribute($key, $value)
{
if (in_array($key, $this->getAmountFields())) {
$value = (int)($value * self::$amountTimes);
}
if (in_array($key, $this->getDates())) {
if ($value != 0 && $value != '') {
$value = is_int($value) ? date('Y-m-d H:i:s', ($value * 1000)) : $value;
}
}
parent::setAttribute($key, $value);
}
//获取model金额字段的设置
public function getAmountFields()
{
return (property_exists($this, 'amountFields')) ? $this->amountFields : [];
}
//获取model日期字段的设置
public function getDates()
{
//$aaaa = $this->dates;
return (property_exists($this, 'dates')) ? $this->dates : [];
}
}
二 Model中引用
use App\Ship\Parents\Models\AmountAndDateTrait;//金额和日期自动转换
use AmountAndDateTrait;
protected $amountFields = ['money_total', 'money_pay'];//金额字段
protected $dates = ['created_at', 'updated_at'];