Reputation: 37259
I am creating a databsse for my site, which requires that multiple attachments be uploaded by users in different pages. I wish to keep all those attachments in a single table and reference that table from other tables, where the attachment would be required.
Now the issue is how do I do this? I have not been able to work out the logic of it as yet. What I have in mind is:
attachment_tbl:
attach_id
file_name
description
item1_id -> FK
item2_id -> FK
item1_tbl:
item1_id
attachment1
attachment2
item2_tbl:
item2_id
attachment1
attachment2
attachment3
Now how do I save all these attachments in the same table, without having multiple FK in the attachment_tbl, as if I add another item3_tbl, which has attachments, would it mean another FK to be added to the attachments_tbl?
Is there some other simpler and better way to do the same?
Upvotes: 0
Views: 2563
Reputation: 8419
If you do not want multiple foreign_keys in attachment_tbl, then you need to have a bridge table at any cost(if you want t keep the relation:) However It will need an extra field as item_tbl_name to distinguish the records for different item tables. Fetching them back is not that much complex.
item_attachment_tbl:
item_id -> FK
item_tbl_name
attach_id -> FK
Upvotes: 0
Reputation: 74028
Add a relationship table, which connects items and attachments, with a one to many relation:
attachment_tbl:
attach_id
file_name
description
item_tbl:
item_id
item_attachment_tbl:
item_id -> FK
attach_id -> FK
For each attachment, there will be a row in the item_attach table:
item_id attach_id
-----------------
item1 attach1
item1 attach2
item2 attach3
item3 attach4
item3 attach5
item3 attach6
When you want to see the attachments of an item, you must join the tables:
select a.file_name, a.description
from attachment_tbl a
inner join item_attachment_tbl ia on a.attach_id = ia.attach_id
where ia.item_id = 87;
See also SQL Fiddle
Upvotes: 4