Laravel 当前在 Carbon 迁移中的时间戳

dum*_*Die 1 migration timestamp laravel php-carbon

我想将created_at显示为时间戳,如下所示:

created_at : 1625501162

这是我在迁移中的created_at列:

$table->string('created_at')->Carbon::now()->timestamp;

现在我希望在创建新记录时自动创建该字段并记录当前时间。所以当我将行更改为:

$table->string('created_at')->useCurrent(Carbon::now()->timestamp);

给我这个错误:

Method call is provided 1 parameters, but the method signature uses 0 parameters

那么我该如何解决这个问题呢?

您建议使用哪些其他方法来创建时间戳并自动存储它?

ker*_*olz 6

如果您希望您的列成为时间戳,您应该使用timestamp()而不是string(). useCurrent()不带参数。改变

$table->string('created_at')->useCurrent(Carbon::now()->timestamp);
Run Code Online (Sandbox Code Playgroud)

$table->timestamp('created_at')->useCurrent();
Run Code Online (Sandbox Code Playgroud)

https://laravel.com/docs/8.x/migrations#column-method-timestamp

https://laravel.com/docs/8.x/migrations#column-modifiers

编辑:始终获取时间戳而不是可以使用的日期

protected $casts = ['created_at' => 'timestamp'];
Run Code Online (Sandbox Code Playgroud)

在你的模型中。