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

Jac*_*chi 5 php laravel eloquent sql-timestamp

这是我的迁移架构:

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

但是当我执行时php artisan migrate,我收到此错误:

Illuminate\Database\QueryException : SQLSTATE[42000]: 语法错误或访问冲突:1067 'timestamp2' 的默认值无效(SQL:创建表objectsidint unsigned not null auto_increment 主键,timestamp1timestamp not null,timestamp2timestamp not null)默认字符集utf8mb4 整理 utf8mb4_unicode_ci)

我必须指出,当我删除 2$table->timestamp(...);行之一时,它可以工作,但当两者都存在时就不行。而Object.php模型是空的,因为它可以。我做错了吗?

我已经阅读了这篇文章,但即使我更改timestamp(...)为时不再有错误dateTime(...),我也只想要时间戳。

Jac*_*chi 12

时间戳有点特殊,它们要么可以为空,要么必须具有默认值。因此,您必须在timestamp('timestamp1')->nullable();timestamp('timestamp1')->useCurrent()或自定义默认值之间进行选择,例如timestamp('timestamp1')->default(DB::raw('2018-01-01 15:23')).

  • WTF Mysql!?为什么我们不能像其他列一样要求在插入时设置时间戳?真让人头疼啊。 (5认同)