如何在 Laravel 中投射时间?

Phi*_*ine 5 laravel

我试图从 08:00:00 到 08:00 获取 TimeString。

我想这样投射时间:

protected $casts = [
    'opens' => 'time:H:i',
    'closes' => 'time:H:i',
];
Run Code Online (Sandbox Code Playgroud)

不使用像 getOpensAttribute() 这样的修改器。

在我的迁移中,我正在使用:

$table->time('opens')->nullable();
$table->time('closes')->nullable(); 
Run Code Online (Sandbox Code Playgroud)

是否可以?

小智 7

我认为你可以创建一个自定义演员表,例如:

使用以下命令生成自定义演员表:

php artisan make:cast TimeCast
Run Code Online (Sandbox Code Playgroud)

时播

public function get($model, string $key, $value, array $attributes)
{
    return  Carbon::parse($value)->format('H:i');
}
Run Code Online (Sandbox Code Playgroud)

最后你可以用它作为

protected $casts = [
    'your_time_to_cast' => TimeCast::class
];
Run Code Online (Sandbox Code Playgroud)


小智 1

根据文档,唯一支持的转换类型是:

整数、实数、浮点、双精度、字符串、布尔值、对象、数组、集合、日期、日期时间和时间戳。

因此,您必须在存储时间之前或从数据库检索时间之后将时间转换为字符串。