我想使用Laravel Schema Builder/Migrations创建一个默认值为CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP的时间戳列。我已经多次阅读Laravel文档,我不知道如何将其作为时间戳列的默认值。

timestamps()函数将它所生成的两列的默认值设置为0000-00-00 00:00。


当前回答

如果你想为一个datetime列设置当前的日期时间(就像我在谷歌搜索时那样),使用这种方式

$table->dateTime('signed_when')->useCurrent();

其他回答

创建created_at和updated_at列:

$t->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$t->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));

你需要MySQL版本>= 5.6.5有多个列的CURRENT_TIMESTAMP

从Laravel 5.1.26开始,标签为2015-12-02,添加了useCurrent()修饰符:

Schema::table('users', function ($table) {
    $table->timestamp('created')->useCurrent();
});

PR 10962(随后是commit 15c487fe)导致了这一添加。

您可能还想阅读感兴趣的第3602和11518期。

基本上,MySQL 5.7(默认配置)要求您为时间字段定义一个默认值或可空值。

它将100%工作。通过这种方式,您可以在更改列的datetype后设置默认的datetime值。

Schema::table('table_name', function (Blueprint $table) {
            $table->dateTime('ans_time')->default(now())->change();
        });

在laravel 7,8中设置当前时间使用以下方法:

$table->timestamp('column_name')->useCurrent();

如果你想为一个datetime列设置当前的日期时间(就像我在谷歌搜索时那样),使用这种方式

$table->dateTime('signed_when')->useCurrent();