Question

My database designs have previously been rather linear, so I'm getting stumped on what is probably a very easy to solve problem.

I have a table of "POSTS", which contain posts which may be a child of either a "CATEGORY" or a "TOPIC". What would be the best way to define the foreign key(s) for the "POSTS" table?

I suppose I could have a column named POST_CATEGORY_ID and a field named "POST_TOPIC_ID, which could be nullable, but this just doesn't sound right. Surely there is a simple solution that I'm missing!

Was it helpful?

Solution

You could do many-to-many relationships between POST and CATEGORY and POST and TOPIC:

POST
----
ID
Text ...
...

CATEGORY
--------
ID
Name

TOPIC
-----
ID
Name

POST_CATEGORY
-------------
POST_ID (FK)
CATEGORY_ID (FK)

POST_TOPIC
----------
POST_ID (FK)
TOPIC_ID (FK)

This way, a post can be associated with any number of categories and topics.

OTHER TIPS

You're on the right track with nullable POST_CATEGORY_ID and POST_TOPIC_ID fields. This will model that a post optionally be related to a category and optionally related to a topic.

If this is meant to be exclusive and mandatory, you will need to add a check constraint that either is null, but not both.

I think a foreign key declaration can only refer to a single table:

FOREIGN KEY(CATEGORY_ID) REFERENCES CATEGORY(CATEGORY_ID);
FOREIGN KEY(TOPIC_ID) REFERENCES TOPIC(TOPIC_ID);

If I'm correct, you'll have to have two foreign keys, one for the CATEGORY table and another for TOPIC, and both need to be nullable.

How about having the categories and topics in the same table

create table topics_categories( id number, description varchar2(100), item_type char(1)); --C or T

Then a single foreign key to topics_categories

The best way is to use Inheritance. You will have two specializations of "Posts": "Posts_Category" and "Posts_Topic" Both have "post_id" (which relates to the parent table "Posts") and another field:

"Category_ID" ("Posts_Category")

"Topic_ID" ("Posts_Topic")

If this sounds confuse look at Doctrine (PHP ORM) at their documentation: http://www.doctrine-project.org/documentation/manual/1_0/en/inheritance

If you want to define foreign keys in the database, the solution that you're suggesting sounds right. I also suggest writing some code in a trigger to make sure that both fields aren't null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top