cchapman
cchapman

Reputation: 3367

Is it better practice to add foreign keys in a separate migration in Laravel (or in any migration workflow for that matter)?

I've been running into a few problems here and there trying to do migrations in Laravel. The more tables I have, the more times I'm trying to redo my migrations, and I'm running into several Foreign Key Constraint errors when one migration runs before with a foreign key based in a table that has not been created yet.

Are there problems that could arise in simply creating all of the tables in their own individual migrations, and then going through with a specific Foreign Key migration? Is there a way to specify it to always be run last? And should each table with foreign keys have its own migration per table, or would it be cleaner to have all of the foreign keys contained in one migration?

I hope this doesn't come off as too subjective. Everything I've seen so far in terms of building the model layer in Laravel seems very methodical with specific ways in doing things. I'm not sure if I just haven't found the workflow documentation for this process yet.

Upvotes: 0

Views: 305

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 153020

Laravel's migration names include a timestamp. For example the default users migration:

2014_10_12_000000_create_users_table.php
^^^^^^^^^^^^^^^^^

Besides creating a unique filename (even if you have create_users_table twice) this timestamp serves the purpose of putting the migrations in an order. To be precise, the order in which the developer created them.

The result of this is that migrations always run in the order you added them

This should usually help with foreign key problems. If you build up your table migration by migration you should be fine with adding foreign keys directly.

However if you are converting an existing database (schema) into Laravel migrations you either have to:

  1. Pay very close attention to the order in which you have to create the tables so all tables the new one depends on already exist.
  2. Just add the foreign keys afterwards like you suggested

I don't think the idea of adding the foreign keys separately is a bad idea. However I wouldn't stick with it for new migrations. Meaning if you decide you need one new table that has foreign key constraints to another, already existing table, just add the constraints directly. There's no need for an extra migration then.

Upvotes: 1

Related Questions