LoginSignup
4
4

More than 3 years have passed since last update.

laravel6で既存のDB(MySQL)からmigrationファイルを作成する

Posted at

サイトをリニューアルするにあたり、既存のDBをそのまま引き継ぐという案件の対応で、migrationファイルをサクッと作ったときのメモ。

「DBからmigrationファイル作成したい」ということでググると、上位にヒットするページが解説するには、以下のジェネレーターで作れるとのこと。

Xethron/migrations-generator
https://github.com/Xethron/migrations-generator

で、実際に試してみたところ、どうやらLaravel6ではエラーになった。
まぁ、最終更新日が3年前だし当たり前だよね。。。

issue でも報告はされているけど、今後も対応されない雰囲気。

コメントを見ると Laravel6 の場合は以下を使うといけるみたい。

oscarafdev/migrations-generator
https://github.com/oscarafdev/migrations-generator

インストール等は、github上に書いてあるので省略。

インストール後、以下のコマンドでOK。

php artisan migrate:generate

以上、メモ終わり。

無事、私の環境でもmigrationファイルが簡単に作成できました。

※補足

migrationファイルは問題なく作成できたんですが、作成したmigrationファイルでテーブルを再作成しようとすると以下のエラーが発生


$ php artisan migrate:refresh --seed

~省略~

   Illuminate\Database\QueryException  : SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 3072 bytes

  at /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:669
    665|         // If an exception occurs when attempting to run a query, we'll format the error
    666|         // message to include the bindings with SQL, which will make this exception a
    667|         // lot more helpful to the developer instead of just the database's errors.
    668|         catch (Exception $e) {
  > 669|             throw new QueryException(
    670|                 $query, $this->prepareBindings($bindings), $e
    671|             );
    672|         }
    673|

  Exception trace:

  1   Doctrine\DBAL\Driver\PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 3072 bytes")
      /var/www/html/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:123

  2   PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 3072 bytes")
      /var/www/html/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:121

  Please use the argument -v to see more details.

調べると Laravel6 の問題ではなく MySQLのバージョンに依存するものらしい。

Laravelはデータベース中への「絵文字」保存をサポートするため、デフォルトでutf8mb4文字セットを使っています。バージョン5.7.7より古いMySQLや、バージョン10.2.2より古いMariaDBを使用している場合、マイグレーションにより生成されるデフォルトのインデックス用文字列長を明示的に設定する必要があります。AppServiceProvider中でSchema::defaultStringLengthを呼び出してください。

というわけで、以下を追加することで再作成成功。

public function boot()
{
    \Illuminate\Support\Facades\Schema::defaultStringLength(191);
}
4
4
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
4
4