Skip to content
Advertisement

How do I keep data B on a child table that is connected to data A on the parent table, while deleting data A on the parent table?

I’m creating a forum-type web app where users can leave comments based on a specific topic. There are registration and login steps. Right now, when a user account is deleted, everything tied to the user is also deleted, such as the comments.

Is there a way to keep the user-generated comments, but delete the user account? And replace the username with “deleted”? Do I simply remove ON DELETE CASCADE from the migration step when creating the comments table?

Thank you.

Advertisement

Answer

One option would be to change the foreign key definition to on delete set null instead of on delete cascade – this also requires making the column nullable (which it currently isn’t):

As explained in the documentation, this option causes the referencing column(s) in the referencing row(s) to be set to nulls […], when the referenced row is deleted.

Side note: in general, I would not actually recommend deleting users from your referential table. Instead, you could have another column in table users that indicate that the user was deleted (say, a boolean column called active), and that you could use as a filter in your queries. This is safer in some ways, and avoids the need to play around with the foreign key later on.

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