Laravel 5.4: DBマイグレーションでエラーになる
What?
このバージョンで
laravel vagrant master %$ php artisan --version Laravel Framework 5.4.10 laravel vagrant master %$ mysql --version mysql Ver 14.14 Distrib 5.7.17, for Linux (x86_64) using EditLine wrapper laravel vagrant master %$ php -v PHP 7.1.1-1+deb.sury.org~xenial+1 (cli) (built: Jan 20 2017 09:20:20) ( NTS ) Copyright (c) 1997-2017 The PHP Group Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies with Zend OPcache v7.1.1-1+deb.sury.org~xenial+1, Copyright (c) 1999-2017, by Zend Technologies with blackfire v1.14.3~linux-x64-non_zts71, https://blackfire.io, by Blackfireio Inc.
このmigrationファイルを
/** * Run the migrations. * * @return void */ public function up() { Schema::create('articles', function (Blueprint $table) { // ここから $table->increments('id'); $table->string('title'); $table->text('body'); $table->timestamps(); $table->timestamp('published_at'); // ここまで追加 }); }
migrateすると、エラーになる
$ php artisan migrate [Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'published_at' (SQL: create table `articles` (`id ` int unsigned not null auto_increment primary key, `title` varchar(255) not null, `body` text not null, `created_at` timestamp nul l, `updated_at` timestamp null, `published_at` timestamp not null) default character set utf8mb4 collate utf8mb4_unicode_ci) [PDOException] SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'published_at'
Solution
このmigrationファイルをちょっと書き換え、
/** * Run the migrations. * * @return void */ public function up() { Schema::create('articles', function (Blueprint $table) { // ここから $table->increments('id'); $table->string('title'); $table->text('body'); $table->timestamps(); $table->timestamp('published_at')->useCurrent(); // ここ追加 // ここまで追加 }); }
こうする
$ php artisan migrate:refresh --seed Rolled back: 2014_10_12_100000_create_password_resets_table Rolled back: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_100000_create_password_resets_table Migrated: 2017_02_14_184315_create_articles_table Migrated: 2017_02_23_172823_add_excerpt_to_articles_table
Why?
- マイグレーションを全部ロールバックし、再度実行する力技コマンド
php artisan migrate:refresh --seed
を使って、強制帳消し published_at
がnot null
なのに値が入ってなかったので、useCurrent()
を使って突っ込んだ
失敗例
published_at
だけ触ればいいのに、その前のtimestampも色々いじってしまった結果。
laravel vagrant master %$ php artisan migrate [Symfony\Component\Debug\Exception\FatalThrowableError] Call to a member function useCurrent() on null laravel vagrant master *%$ php artisan migrate [Symfony\Component\Debug\Exception\FatalThrowableError] Call to a member function default() on null laravel vagrant master *%$ php artisan migrate [Symfony\Component\Debug\Exception\FatalThrowableError] Call to a member function nullable() on null
config/database.phpの確認したけど、ちゃんとstrictになってた
'strict' => true,