«

hyperf框架 model casts 自定义类

时间:2024-4-9 14:10     作者:xiang     分类: php


<?php
namespace App\Transformers;
use Hyperf\Contract\CastsAttributes;
class AmountTransformer implements CastsAttributes
{
    public function get($model, $key, $value, $attributes) :float
    {
        // 在这里对amount字段的值进行自定义转换
        // 例如,保留两位小数
        return (float) $value;
    }

    public function set($model, $key, $value, $attributes)
    {
        return $value;
    }
}

实现CastsAttributes接口

调用

<?php

declare(strict_types=1);

namespace App\Model;

use App\Transformers\AmountTransformer;

class CollectionModel extends Model
{
    protected ?string $table = 'collection';

    protected array $casts = ["amount" => AmountTransformer::class];
}