Search code examples
phpmysqllaravellaravel-5

Creating a category and subcategory system to news management


I'm creating a news website, and in the news website will have a category and subcategory management, I already created the tables and also can manage categories and subcategories, the only issue is regarding how I will associate the posts with the categories in my create post, should I create in my table "posts" create 2 columns, the "category_id" and the "subcategory_id"? It doesn't look quite correct, since only by giving one of them I should already no which one is category and subcategory, and I would no if my categories and subcategories column were only one, but in my case it isn't. I feel how I created my tables for posts, categories and subcategories is not quite how should it be, here I leave my code:

Posts:´
-id;
- title;
- body;

Categories:
- id;
- name;

Category_Subcategory:
- id;
- name;
- category_id;

So how should I associate the category or subcategory to posts? Is this the correct way I'm doing it?


Solution

  • I you could use a self-parenting relation for the categories. This can allow you to create a n-level of categories (you can limit that on your source code)

    Categories:
     - id
     - name
     - parent_id (FK to Categories.id, Null if is a root category)
    
    Posts:
     - id
     - title
     - content
     - category_id
    

    So, example:

    Category [#1, 'Financial', NULL] = Root category Financial
    Category [#2, 'Crisis', 1] = Sub-category linked to Financial one
    

    You have another solution: many-to-many-polymorphic-relations You can create a relation post to category and another post to subcategory

    https://laravel.com/docs/5.3/eloquent-relationships#many-to-many-polymorphic-relations