5

这是我的迁移架构:

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]:语法错误或访问冲突:1067 'timestamp2' 的默认值无效(SQL:创建表objectsidint unsigned not null auto_increment 主键,timestamp1timestamp not null,timestamp2timestamp not null)默认字符集utf8mb4 整理 utf8mb4_unicode_ci)

我必须指出,当我删除$table->timestamp(...);两条线中的一条时,它可以工作,但是当两者都存在时它不会。Object.php模型是空的。我犯错了吗?

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

4

3 回答 3

13

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

于 2018-05-03T15:49:15.167 回答
3

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

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

于 2018-05-03T13:50:48.637 回答
2

您可以使用使两个时间戳之一为空

timestamp()->nullable();

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

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

laravel 还通过使用内置了时间戳

$table->timestamps();

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

于 2018-05-03T13:53:01.060 回答