jasonherndon's avatar

Are Foreign Keys ALWAYS a good idea? #FK

So I'm in love with how easy it is to add and define foreign key constraints within Laravel. My question is not about how to do them as much as it is - should I always be adding them - or just salt/peppering them where I'm okay with permanent data loss due to cascading deletes?

While I get all of the benefits of cascading deletes I've read online that cascading deletes aren't always wanted in some applications (like e-commerce sites). I build a lot of learning-based sites where content is reusable and the thought of such easy and permanent data destruction freaks me out.

For example,

In a user based site, I can see the benefit in having all comments for a post deleted when the post is deleted so they aren't orphaned. But what about users and my access logs? If a user's account is deleted, and I've set up the foreign key on the access log, and those get deleted I may be loosing data I want later. Especially if I need to restore the user.

Should I serialize and store records in some sort of log before performing the deletes so I can restore it later if needed?

0 likes
5 replies
jasonherndon's avatar

@danielboendergaard - So you recommend soft deleting such records and then when forceDelete(); is called it's respective foreign key constraints kick in a get deleted as well, correct?

danielboendergaard's avatar

Yes, I think that is a perfect fit for your use case, you wont have any problems with foreign keys and it is very easy to restore models.

jasonherndon's avatar

@danielboendergaard I had thought of soft deleting but always thought of it as foreign keys/cascading deletes vs soft deleting - but the forceDelete() method seems to give you the best of both worlds. Thanks for the comment.

JarekTkaczyk's avatar

It's completely different layer of control.

Foreign keys are not required at all in the context of Eloquent (and code layer in general) . There are much more features than just cascade deleting that you're referring to.

Think of it like of validation: most likely you have JS layer of validation on the client-side, but you must have also server-side validation in your PHP layer. The same goes for the PHP layer and DB layer of control of your data.

Now, about the logs - keeping logs dynamic is a bad idea. Logs should hold static data and should not be subject to change in the future.

Btw that is why I created this little package: https://github.com/jarektkaczyk/revisionable

Please or to participate in this conversation.