Skip to content
Advertisement

How to add constraints to existing keys using laravel migration

I currently have a database in my project which has already been put in production. But I didn’t use constraints in the previous migrations. Now I have tables products, shops and an intermediate table product_shop. The problem is that if I delete any product, that has been put on some shop, the pivot is still kept in the intermediate table. I need to force the referential integrity of my database, even though no product/shop has been changed/deleted yet.

I don’t want to use Laravel’s event listeners, because they do not work when I delete an object without retrieving it first. Let’s consider this existing structure, where I have data I don’t want to lose:

JavaScript

Now I want to create a migration, where I set constraints to product_shop.product_id and product_shop.shop_id with onDelete: CASCADE, onUpdate: CASCADE. So no matter where or how I will delete a product – if I delete one, all the related pivots will be deleted as well.

But how am I suppose to change constraints in migration->up() & migration->down()?

JavaScript

Thank you 🙂

Advertisement

Answer

Solution found:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement