Category Hierarchy (in order) using PHP MySQL

妖精的绣舞 提交于 2019-12-10 15:46:37

问题


I am trying to ORDER my all categories and sub-categories in a hierarchy:

The main point is how to get them from MySQL ORDERLY (using POSITION field)

  • Cat A --> position 10
    • Sub-Cat 1 --> position 10
    • Sub_Sub_Cat 1 --> position 20
      • Sub_Sub_Cat 2 --> position 10
    • Sub_Cat 2 --> position 30
  • Cat B --> position 20
  • Cat C --> position 30

MySQL code:

 CREATE TABLE IF NOT EXISTS `categories` (
   `category_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
   `position` smallint(5) unsigned,
   `parent_id` mediumint(8) unsigned NOT NULL DEFAULT '0'
  PRIMARY KEY (`category_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 ;

回答1:


You want to traverse the tree using SQL? That is not possible with the adjacency list model, you have to use the nested sets model. Then you can just ORDER BY left to get the whole tree in the correct order.



来源:https://stackoverflow.com/questions/4554968/category-hierarchy-in-order-using-php-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!