Home > Enterprise >  Lumen migration - Foreign Id with a table name that isn't the plural of the local key
Lumen migration - Foreign Id with a table name that isn't the plural of the local key

Time:02-20

How can I create a Lumen migration with a column that references a table that has an unrelated name to the column name?

Example:

The following would throw an error that user_destinations can't be found.

$table->foreign('user_destination')->references('id')->on('locations');

or

$table->foreignId('warehouse_isle_shelf_id')->constrained();

The intention here is for it to look for warehouse_isles instead of warehouse_isle_shelves or warehouse_isle_shelfs as I'm not sure how Lumen handles plurals for words who's plurals aren't just taking the singular form and appending an s.

CodePudding user response:

Your code here should work because you have referenced the table name locations:

$table->foreign('user_destination')->references('id')->on('locations');

But the second line is asking Laravel to guess the name. Here's the relevant part talking about it in the documentation:

The foreignId method is an alias for unsignedBigInteger while the constrained method will use convention to determine the table and column name being referenced. If your table name does not match the convention, you may specify the table name by passing it as an argument to the constrained method:

$table->foreignId('user_id')->constrained('users');
  • Related