Reputation: 3367
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
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:
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