在 laravel 10 / php 8.2 时间中我有一个时间字段,并且在模型中我定义了转换:
<?php
namespace App\Casts;
use Carbon\Carbon;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
class TimeCast implements CastsAttributes
{
public function get(Model $model, string $key, mixed $value, array $attributes): mixed
{
return Carbon::parse($value)->format('H:i');
}
public function set(Model $model, string $key, mixed $value, array $attributes): mixed
{
return $value;
}
}
在 Item 模型中:
protected function casts(): array
{
return [
'time' => TimeCast::class,
];
}
我需要 Carbon 值(时间为零)来添加其他时间字段。我这样做:
$calcDate = Carbon::parse(Carbon::now(\config('app.timezone')))->startOfDay();
$calcDate->addDays(5);
$item = Item::find($id);
$dateTill = $calcDate->addMinutes($item->time);
dd(Carbon::parse($dateTill));
但在 $dateTill 中我只看到 $calcDate 值(+5 天,不含时间)。
我该怎么做?
您正在将“H:i”传递到 addMinutes 函数,并且该方法仅接受整数值。
一个选项是,在您的转换选项中,您将返回以分钟为单位的值,并且您可以直接将其传递到 addMinutes 中。
在第二个选项中,您将时间作为 Carbon 实例返回,并在时间加法函数中进行修改。
如果您想添加秒数,也可以在上面添加。在第一种情况下,您需要返回秒数,并在计算时添加秒数。