Home > database >  How can I in migration to set index name automatically manually?
How can I in migration to set index name automatically manually?

Time:01-18

In laravel 9 app running migration with statement(mysql database) :

$table->foreignId('notification_config_id')
 ->nullable()
 ->references('id')
 ->on('notification_configs')
 ->onUpdate('RESTRICT')
 ->onDelete('RESTRICT');

I got error :

SQLSTATE[42000]: Syntax error or access violation: 1059 Identifier name 'notification_configs_notification_types_notification_config_id_foreign' is too long (SQL: alter table notification_configs_notification_types add constraint notification_configs_notification_types_notification_config_id_foreign foreign key (notification_config_id) references notification_configs (id) on delete RESTRICT on update RESTRICT)

looks like name of the index is set automatically, can I set it manually ? I tried :

$table->foreignId('notification_config_id')
 ->nullable()->references('id')
 ->on('notification_configs')
 ->onUpdate('RESTRICT')
 ->onDelete('RESTRICT')
 ->name('notification_configs_longname_ref');

But the same error anyway... How that can be fixed?

Thanks!

CodePudding user response:

Instead of $table->foreignId() you can use $table->foreign(). Method foreign() accepts a second paramater as name of the key. So your migration code could include something like this :

$table->foreign('notification_config_id', 'notification_config_foreign_id')->nullable()->references('id')->on('notification_configs')->onUpdate('RESTRICT')->onDelete('RESTRICT');
  • Related