Carbon toTimeString 不更新

Carbon toTimeString not updating

我正在进行更新,并通过 Carbon::now();

获取日期
$dt = Carbon::now();                  
'date'          => $dt->toDateString(),
'time'          => $dt->toTimeString(),

当我检查数据库时,我的日期字段具有基于今天日期的正确日期字符串。当我检查时间字段(MySQL 中的日期时间字段)时,我只看到 0000-00-00 00:00:000 并且没有任何更新。

我是否需要将数据库字段类型更改为其他内容,或者我是否需要调用不同的内容来从 Carbon::now(); 中获取时间? ?

您应该将数据存储为时间戳。

然后也许向您的模型添加一个日期修改器,将它们变成碳实例。

class User extends Model
{
    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at'
    ];
}

https://laravel.com/docs/5.4/eloquent-mutators#date-mutators

然后当 outputting/using 日期时,您可以使用 carbon 的字符串格式..

$this->created_at->toTimeString()  // 14:15:16

datetime 字段需要一个像 YYYY-MM-DD HH:MM:SS 这样的字符串,但是 toTimeString 函数 returns 只有 HH:MM:SS 部分。当您尝试将其插入数据库时​​,MySQL 不知道如何处理它,因此它只是将该字段设置为 0000-00-00 00:00:00

在日期时间字段中插入时,请改用函数 toDateTimeString()

'date'          => $dt->toDateString(),
'time'          => $dt->toDateTimeString(),

检查您是否将日期和时间列与其他 $fillable 一起放入模型中。

class YourModel extends Model
{
    protected $fillable = [
       'date_column',
       'time_column',
   ];
}