All items in the items table have a category that can be derived from the item_category table.
+---------------------------------------------+
| items |
+---------------------------------------------+
| id | PK |
+--------------------+------------------------+
| item_category_id | FK(item_categories.id) |
+--------------------+------------------------+
The item_category table references itself. I wanted to create a category->sub-category->sub-sub-category etc. system. I don't know how many nested sub-categories there will be so I thought my best bet would be to enclose that structure in a single table. If the item_category_id is NOT NULL then it has a parent, otherwise it is a super-category and does not have a parent.
+-------------------------------------------+
| item_categories |
+-------------------------------------------+
| id | PK |
+------------------+------------------------+
| item_category_id | FK(item_categories.id) |
+------------------+------------------------+
This is where my question lies. The doll_item table is a pivot table. Basically a doll can have many items and an item can belong to many dolls. But there's more to it than that. I want to make sure that for every doll, in the doll_item table, its corresponding item comes from a unique category.
I have tried to pull in the item_category_id for the item in each row; however, I fear that this relation does not enforce that the item_id and item_category_id from the items table necessarily come from the same row. Without this requirement, the addition of the two latter rows in the doll_item table is pointless.
Is it possible to enforce this using MySQL?
+-------------------------------------------------------+
| doll_item |
+-------------------------------------------------------+
| doll_id | FK(dolls.id) |
+----------------------+--------------------------------+
| item_id | FK(items.id) |
+----------------------+--------------------------------+
| item_category_id | FK(items.item_category_id) |
+----------------------+--------------------------------+
| unique(doll_item.doll_id, doll_item.item_category_id) |
+-------------------------------------------------------+
Thanks