![]() |
migration and foreign keys with non empty table - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5) +--- Forum: Best Practices (https://forum.codeigniter.com/forumdisplay.php?fid=12) +--- Thread: migration and foreign keys with non empty table (/showthread.php?tid=87644) |
migration and foreign keys with non empty table - lingtalfi - 05-13-2023 Hi, I'm new to this migration concept, and, using 4.3.3, I have a "user" table, and a "task" table, both independent yet. They already exist and have some records in it. Now I just want to create a migration that adds a foreign key that makes "task.user_id" reference "user.id". Here is my code: PHP Code: <?php So, the code above will work (php spark migrate) only if the "task" table is empty. If it's not, I have a "Cannot add or update a child row: a foreign key constraint fails..." error. Fair enough, because now I'm just playing with CodeIgniter in development, but then I wonder, what happens when my website is in production and I need to do similar changes? So my question is: is this the regular/best practice workflow for a migration that adds a foreign key to a non-empty table? Is my code okay? And should i backup my data first, then empty the table, then apply the migration, then put the data back ? Or is there something I missed ? What's the best practice workflow for adding a foreign key to an existing non-empty table? Thanks for your advices. Cheers, Ling. |