Can I rely on MySQL Cascade for uninstallation?

I am using PHP Laravel Framework, but this is a general PHP question. Is it possible to use MySQL foreign key relationship to delete cascade to delete related rows? Or is this the best way to do it in PHP? I think the waterfall system is really good, but don't know if it's safe to use it? Any best practices?

For example, if you have a user who created posts and that user is deleted, are you deleting their posts using PHP, then deleting the user, or are you just using a cascade?

Thanks for your feedback.

+3


source to share


1 answer


Yes, you can rely on CASCADE removal. If you define a relationship with ON DELETE CASCADE, the foriegn line will definitely be deleted. Using ON DELETE CASCADE is definitely recommended (if you want to delete related rows), and most likely more reliable than implementing the delete cascade in your application.

In the example you provided, rows containing user posts were linked to the user using a foreign key with ON DELETE CASCADE. In this case, you just delete the user. MySQL will follow all relationships and remove all related rows. This will prevent lost data. Doing this with an application is much more "risky" in terms of the potential for data orphanhood.



However, if there are other relationships with the same data (for example, there are response messages related to the user's message to be deleted), the deletion can be blocked because the link in the response line will dangle. Of course, it all depends on the design of your database and how you set up foreign keys.

+3


source







All Articles