laravel / lumen dateformat'U'实际上是如何工作的?

问题描述 投票:-1回答:2

我无法获得日期格式“U”在流明中工作的时间戳。

在迁移中:

        $table->timestamps();

在模型中:

protected $dateFormat = 'U';

protected $dates = [
    'created_at',
    'updated_at',
    'deleted_at'
];

public function getDateFormat()
{
    return 'U';
}

从控制器插入行:

    $model = new ApiKey;
    $model->random= rand();
    $model->name = $name;
    $model->scope = $scope;
    $model->save();

它确实在数据库中插入了行,但是对于created_at和updated_at列,其值为00:00:00。

此外,在通过toArray或toJson检索模型时,它抛出异常:

enter image description here

我希望流明自动更新时间戳并检索时间戳作为unix时间戳格式,即从1970年1月1日起的秒数。

此外,$table->timestamps()没有创建deleted_at列。我需要做什么才能通过laravel创建此列。

除了$table->timestamp('deleted_at');还有其他选择吗?

我发现一个解决方案托架将时间戳列更改为int。但是我希望用laravel方式完成这些事情。

laravel lumen
2个回答
1
投票

Unix时间戳是整数,与SQL datetime / timestamp字段不兼容。如果要使用unix时间戳,请使用整数字段类型进行存储。

timestamps()方法仅创建created_at和updated_at,默认情况下不启用软删除。如果需要整数存储,则不应使用此方法。


If you only want to change the output format when serializing data, use casting:`

/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = [
    'created_at' => 'datetime:U',
];

0
投票

这很可能是因为Laravel / Lumen创建的日期/时间列为timestamp而不是int,所以你试图在字段中保存错误类型的数据,导致0000-00-00 00:00:00

这也会导致碳问题,因为你尝试使用与内容相比错误格式的createFromFormat

您可以在迁移中使用$table->integer('deleted_at');来创建deleted_at列。

TL; DR:

使用$table->integer('updated_at')手动创建日期时间列。

© www.soinside.com 2019 - 2024. All rights reserved.