1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravelのmigrationでtimestamp型がInvalid default value for ''エラー

Posted at

以下のマイグレーションファイルを作成し実行した。

public function up()
{
  Schema::create('events', function (Blueprint $table) {
    $table->id();
    $table->string('name', 255);
    $table->timestamp('start_datetime');
    $table->timestamp('end_datetime');
    $table->timestamps();
  });
}

すると、以下のエラーが発生した。
ちなみにこのSQLをDBに直接実行すると正常にテーブル作成が完了する。
なのでSQLのエラーと言うよりLaravelのエラー。

SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'end_datetime' (SQL: create table `events` (`id` bigint unsigned not null auto_increment primary key,`name` varchar(255) not null, `start_datetime` timestamp not null, `end_datetime` timestamp not null, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')

で、解決方法としてはtimestampはデフォルト値を設定するか、Null許容にする必要があるらしい。

public function up()
{
  Schema::create('events', function (Blueprint $table) {
    $table->id();
    $table->string('name', 255);
    $table->timestamp('start_datetime')->default(DB::raw('CURRENT_TIMESTAMP'));
    $table->timestamp('end_datetime')->default(DB::raw('CURRENT_TIMESTAMP'));
    $table->timestamps();
  });
}

ドキュメントには特に記載なかったので、↓を参考に。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?