LoginSignup
0
0

More than 1 year has passed since last update.

Laravelのマイグレーションで長い名前のカラムに外部キー制約を付けるときにはconstraint()ではなくforeign()を使う

Posted at

長い名前のカラムに対してつけようとしたところエラーになりました。

migrations/test.php
  $table->foreignId( 'something_tooooooo_much_logn_column_name_and_foreign_table_name_id' )
  ->nullable()
  ->constrained( 'foreign_table' )->onUpdate( 'cascade' )->onDelete( 'cascade' );

Laravelではカラム名と外部テーブル名を使って自動的に外部キー制約名を付けるのですが、その長さの制約に引っかかってしまっています。

migration/hoge.php
  $table->foreignId( 'something_tooooooo_much_logn_column_name_and_foreign_table_name_id' )->nullable();
  // constrainedで外部キー制約を作ると自動で名前付けされるが、その場合には外部キー制約の名前が長すぎてエラーとなる。
  // そのため手動で制約名を付ける
  $table->foreign( 'something_tooooooo_much_logn_column_name_and_foreign_table_name_id',
  env( 'DB_TABLE_PREFIX' ) . 'too_much_long' )->references( 'id' )->on( 'foreign_table' )->onUpdate( 'cascade' )->onDelete( 'cascade' );

※わかりやすいようにカラム名を長くしすぎたので、もしかしたらカラム名の長さ制約に引っかかるかもしれません。

0
0
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
0
0