laravel 中的默认时间戳(create_at 和 updated_at)在保存到数据库时采用什么格式?

What format does the default timestamps (create_at and updated_at) in laravel have when saved to db?

我要将额外的时间戳保存到数据库:last_sent

我想以与默认时间戳(created_at 和 updated_at)相同的方式保存它 - 这意味着我将像这样迁移它:

$table->timestamp('last_sent')->nullable (有时会为 null..)

我的问题是我应该将时间值的什么格式保存到此列?

我找到了两个选项,但不确定哪个是正确的:

Carbon\Carbon::now()->toDateTimeString();

或者只是

Carbon\Carbon::now();

保存日期和时间以像默认时间戳一样获取日期和时间的正确方法是什么?

我认为这是 Mysql 的事情...

根据mysqltutorial

The MySQL TIMESTAMP is a temporal data type that holds the combination of date and time. The format of a TIMESTAMP is YYYY-MM-DD HH:MM:SS which is fixed at 19 characters.

所以,默认是 YYYY-MM-DD HH:MM:SS

这就是时间戳存储在数据库中的方式...

如果你发现 $table->timestamps();这样做 :

public function timestamps($precision = 0)
{
    $this->timestamp('created_at', $precision)->nullable();

    $this->timestamp('updated_at', $precision)->nullable();
}

所以:laravel 保持 Mysql 格式默认为 precision=0 如果您想像默认 laravel 时间戳一样存储您的列,您可以:

$this->timestamp('last_sent',0)->nullable();

你可以忽略第二个参数

您的列的值:

Carbon\Carbon::now()->toDateTimeString(); 

这行不通,因为它只是一个字符串而不是日期

但这就足够了:

$value=Carbon\Carbon::now();

尽管 $value 将在毫秒内保存四个数字,但由于我们迁移中的(0 精度),这些数字将在 db 中被忽略...

通常为 YYYY-MM-DD Hour:Min:Sec 格式。为了让您清楚,我将为此添加一个屏幕截图。

希望对你有所帮助