Eloquent: 带有时间戳的无效默认值

Eloquent: Invalid default value with timestamps

这是我的迁移架构:

public function up()
{
    Schema::create('objects', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamp('timestamp1');
        $table->timestamp('timestamp2');
    });
}

但是当我执行php artisan migrate时,我得到这个错误:

Illuminate\Database\QueryException : SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'timestamp2' (SQL: create table objects (id int unsigned not null auto_increment primary key, timestamp1 timestamp not null, timestamp2 timestamp not null) default character set utf8mb4 collate utf8mb4_unicode_ci)

我必须指出,当我删除 2 $table->timestamp(...); 行中的其中一行时,它可以工作,但如果同时存在,则不会。 Object.php 模型可能是空的。我弄错了吗?

我已经阅读了 ,但是即使我将 timestamp(...) 更改为 dateTime(...) 时不再出现错误,我只想要时间戳。

我在 laracasts 上找到了 this 解决方案:

nullableTimestamps() 仅适用于默认字段 created_atupdated_at。对于自定义字段,请使用 timestamp()->nullable();

您可以使用

使两个时间戳之一可为空
timestamp()->nullable();

使用您的示例,您将使用:

$table->timestamp('timestamp2')->nullable();

另外 laravel 使用

内置了时间戳
$table->timestamps();

它将自动为您处理 updated_at 和 created_at 时间戳

时间戳有点特殊,它们要么可以为空,要么必须有默认值。因此,您必须在 timestamp('timestamp1')->nullable();timestamp('timestamp1')->useCurrent()timestamp('timestamp1')->default(DB::raw('2018-01-01 15:23')).

等自定义默认值之间进行选择