If I have two tables: A (id, … some other columns) and B (id, … some other columns). I need to associate Comments (another table: id, text, author) with A and B objects.
Can I do something like creating the fourth table for that purpose: comment_id, table_id (A or B or maybe others), item_id? I mean some sqlalchemy way?
Now I know only of those two solutions:
http://bpaste.net/show/27149/ – for each A and B there will be separate table with comments. I don’t think it’s a good idea, because those tables are (should be) identical, if I want to see all comments by some author – it will be more difficult than the other ways, if there will be C table someday – I will need to create a table for its comments…
Another solution – http://bpaste.net/show/27148/. I think is better, but I still will be needing to create an association table for every table I need to comment the items.
Any ideas? Thanks in advance.
You could try:
It is still a relatively hacky way to do it, but it preserves referential integrity by using foreign keys.
If you’d like to go for the solution where you store the table name, you could try something like this:
I have not tested this myself, so if you run into problems have a look at Specifying Alternate Join Conditions or comment and I will do more research.
For an in-depth explanation of the subject, see Mike Bayer’s blog entry on Polymorphic Associations