在我的几个模型中,我有这样的代码
public function setTotalAttribute($value)
{
return $this->attributes['total'] = $value * 100;
}
public function getTotalAttribute($value)
{
return $value * 0.01;
}
有时我变异的字段称为购买或价格,但代码是相同的(更改7.99到799以存储在数据库中,并在返回时将其更改回来)。
如果所有字段都被命名为相同我可以使用特征,但它们稍有不同....有没有办法可以设置类似于自动变异到Carbon实例的日期字段?
答案 0 :(得分:0)
一种解决方案是在具有此类字段的模型中定义处理美元/美分转换的字段,然后使用特征覆盖全局变更器/访问器。
class Model
{
use HasMoneyFields;
protected $moneyFields = ['purchase', 'price', 'total'];
}
trait HasMoneyFields
{
public function getAttributeValue($key)
{
$value = parent::getAttributeValue($key);
if (property_exists($this, 'moneyFields')) {
if (in_array($key, $this->moneyFields)) {
$value /= 100;
}
}
return $value;
}
public function setAttribute($key, $value)
{
parent::setAttribute($key, $value);
if (property_exists($this, 'moneyFields')) {
if (in_array($key, $this->moneyFields)) {
$this->attributes[$key] = $value * 100;
}
}
}
}
答案 1 :(得分:0)
您可能对https://github.com/topclaudy/eloquent-mutators
感兴趣<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use \Awobaz\Mutator\Mutable;
protected $accessors = [
'title' => 'trim_whitespace',
'content' => 'trim_whitespace',
];
}
该程序包允许您创建自定义访问器/更改器扩展。