简体   繁体   中英

Is it safe to rely on MySQL Cascade for delete

I'm using the PHP Laravel Framework, but it's a general PHP question. Is it safe to use the MySQL foreign key relation on delete cascade to delete related rows ? Or is it a best practice to do it in PHP ? I find the cascade system realy nice but don't know if it's safe to use it ? Any best practices ?

For example when you have a user that have created posts and that user is deleted, do you delete his posts with PHP then delete the user, or just use cascade ?

Thanks for your feedbacks.

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

In the example you gave, the rows containing the users posts were related to the user using a foreign key with ON DELETE CASCADE. In this case, you would just delete the user. MySQL will follow all of the relationships and delete all related rows. This wil prevent orphaned data. Doing it via the application is much more "risky" in terms of the potential for orphaning data.

Keep in mind, however, if there are other relationships to the same data (eg there are reply posts relating to the user's post who is going to be deleted), the delete can be blocked, since the reference in the reply row would be dangling. Of course, this is all dependent on your database design and how you set up your foreign keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM