首页 文章

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

提问于
浏览
3

这是我的迁移架构:

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:create table objects(id int unsigned not null auto_increment primary key,timestamp1 timestamp not null,timestamp2 timestamp not not null)默认字符集utf8mb4 collate utf8mb4_unicode_ci)

我必须指出,当我删除其中一条中的一条时,它可以正常工作,但是当它同时存在时它不会 . 并且 Object.php 模型尽管是空的 . 我犯了错误吗?

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

3 回答

  • 2

    我在laracasts上发现了this解决方案:

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

  • 2

    您可以通过使用使两个时间戳中的一个可以为空

    timestamp()->nullable();
    

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

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

    laravel还使用了内置时间戳

    $table->timestamps();
    

    它会自动处理updated_at和created_at时间戳

  • 1

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

相关问题