我正在创建一个新闻网站,在新闻网站中将有一个类别和子类别管理,我已经创建了表格并且还可以管理类别和子类别,唯一的问题是我如何将帖子与类别相关联我创建的帖子,我应该在我的表“帖子”中创建创建 2 列,“category_id”和“subcategory_id”吗?它看起来不太正确,因为只有给出其中之一,我应该已经没有哪个是类别和子类别,如果我的类别和子类别列只有一个,我也不会,但在我的情况下它不是。我觉得我为帖子、类别和子类别创建表格的方式不太理想,这里我留下我的代码:
Posts:´
-id;
- title;
- body;
Categories:
- id;
- name;
Category_Subcategory:
- id;
- name;
- category_id;
那么我应该如何将类别或子类别与帖子相关联?这是我的正确做法吗?
最佳答案
我可以为类别使用自育关系。这可以让你创建一个 n 级的类别(你可以在你的源代码中限制它)
Categories:
- id
- name
- parent_id (FK to Categories.id, Null if is a root category)
Posts:
- id
- title
- content
- category_id
所以,例如:
Category [#1, 'Financial', NULL] = Root category Financial
Category [#2, 'Crisis', 1] = Sub-category linked to Financial one
你有另一个解决方案:多对多多态关系 您可以创建一个与类别的关系帖子和另一个与子类别的帖子
https://laravel.com/docs/5.3/eloquent-relationships#many-to-many-polymorphic-relations
关于php - 为新闻管理创建类别和子类别系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41198022/