Search code examples
phpmysqltheory

Should the father know about the children or vica versa?


Should the father know about the children or vica versa?

That is, in a situation where I have two kinds of objects (items and categories), each has its own characteristics and fields and we have a relation between them that every item has a category he is in.

I want to ask in two ways about what should happen, in theory and in php + mysql.

Should the categories know about all the items that are in it, or should every item know about its category?

In php + mysql the exact question is should I for every item in its row save its category's id, or should I create a special table for this relation (each row contains a category id and an item id)?


Solution

  • Best practice is the children know about the parents (ex: parent_id). The alternative is not scalable, and very taxing to your system. You could easily run a query to FIND the children though - SELECT * FROM items WHERE item_category = x. The reason for this is when you add or delete items, the category is not affected. It doesn't become a different category because you assign an item to it or remove an item from it, so it shouldn't care either way which items are assigned to it.

    This is different from a tagging setup. In the one-to-many category assignment method, items would fall into a single "category" but might have many "features". Tagging features is a many-to-many relationship and would require the mapping table you mentioned. Assigning parent categories requires only a single "parent" field in the items table.