Quantcast
Channel: User Schwern - Stack Overflow
Viewing all articles
Browse latest Browse all 581

Answer by Schwern for What is the best way to handles comments related to multiple tables in SQL?

$
0
0

If you do one table like (table name, foreign id, ...) you lose referential integrity and important things like on delete cascade. These can be restored with triggers, but it's a lot of work and a lot of chances it can go wrong.

You can do multiple join tables, and this works and has referential integrity. It also has the advantage of giving you a place to put additional information about a particular type of comment; maybe comments about a part needs some additional attributes. but if you want to find out who wrote a comment you have to search all linked tables. This can be eased by creating a view.

create view as commenters  select parts_id as id, comment_id, 'parts' as table_name  from part_comments  union  select persons_id as id, comment_id, 'persons' as table_name  from persons_comments;select * from commenters where comment_id = $1

Some ORMs provide a way to solve this problem with application code. For example, Rails provides polymorphic associations and delegated types. This works if your database will only be accessed through the ORM.


I've been experimenting with a 3rd option that creates an entity called a "commenter". Comments are done by commenters.

create table commenters (  id bigserial primary key,  -- this is for informational purposes  table_name text not null);create table comments (  commenter_id bigint not null references commenters on delete cascade,   body text not null );

Each table which can have comments has a commenter.

create table parts (   id bigserial primary key,   commenter_id bigint not null references commenters on delete cascade );create table persons (   id bigserial primary key,   commenter_id bigint not null references commenters on delete cascade);

To ensure commenters get deleted, we need to add a trigger to each table.

create or replace function delete_associated_commenter()  returns trigger  language plpgsql  as $$    begin      delete from commenters where id = OLD.commenter_id;      return OLD;    end;  $$;create trigger after_delete_parts_commenter_triggerafter delete on partsfor each rowexecute function delete_associated_commenter();create trigger after_delete_persons_commenter_triggerafter delete on personsfor each rowexecute function delete_associated_commenter();

Demonstration.

Does this have advantages over multiple join tables? I'm not sure yet.


Viewing all articles
Browse latest Browse all 581

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>