devondahon's avatar

How to add a index on a constrained foreign key

I'm seeding a CSV file with about 2.000.000 entries into a PostgreSQL database, and some fields need to be dispatched in specific tables with relationship.

For the relationship, I'm using this in my migration:

$table->foreignId('foo_id')->constrained('foos');

When trying to improve the bad seeding performances with PostgreSQL, I realised there's was no index on the profession_id column, so I added one like this:

$table->foreignId('foo_id')->constrained('foos')->index();

But I don't see it in the indexes list of my main table, why ? Also, I don't get any error at migration refresh.

Is it possible to add an index to a foreign key ? If yes, how ?

0 likes
1 reply
GeordieJackson's avatar
Level 18

If you set a foreign key, it's set to an index automatically when the constrained() method is added.

If you look in your database client and look for 'indexes' under 'structure' you should see something like this:

tablename_foo_id_foreign
1 like

Please or to participate in this conversation.