atymic/laravel-dateinterval-cast

1.1.0 2020-09-09 23:43 UTC

This package is auto-updated.

Last update: 2024-09-10 08:06:45 UTC


README

Build Status StyleCI Latest Version on Packagist Total Downloads

Laravel 内置了对 datedatetime 类型的转换,但如果您想使用 ISO 8061 持续时间与本地 DateInterval 类或 Carbon 的 CarbonInterval,那么您将无法使用。

此包提供了两种自定义转换(分别用于 DateIntervalCarbonInterval),利用 Laravel 7.x/8.x 的自定义转换功能。

安装

composer require atymic/laravel-dateinterval-cast

使用此包

在模型中的 $casts 中,将您希望启用转换的属性分配给包提供的转换之一。您应该在数据库表中使用 varchar/string 字段。

class TestModel extends Model
{
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'is_xyz' => 'boolean',
        'date_interval' => DateIntervalCast::class,
        'carbon_interval' => CarbonIntervalCast::class,
    ];
}

模型中的属性将被转换为间隔对象,并以 ISO 8061 持续时间字符串的形式保存到数据库中。如果您尝试分配无效的持续时间(或者在数据库表中存在,并且您使用获取器),将抛出异常。

$model = new TestModel();

$model->carbon_interval = now()->subHours(3)->diffAsCarbonInterval();

$model->save(); // Saved as `P3H`
$model->fresh();

$model->carbon_interval; // Instance of `CarbonInterval`
$model->carbon_interval->forHumans(); // prints '3 hours ago'

try {
    $model->carbon_interval = 'not_a_iso_period'; 
} catch (\Atymic\DateIntervalCast\Exception\InvalidIsoDuration $e) {
    // Exception thrown if you try to assign an invalid duration
}

贡献

欢迎贡献 :) 请创建一个 PR,我会审查/合并。

许可证

MIT