我正在尝试为电子商务网站制作面包屑。像这样的东西:
Home > Kitchen > Serving and reception > Spoon
每一项都是一个标签。因此,
tags
表是基于父级/历史的。这是表结构的示例:
// tags
+----+-----------------------+-----------+
| id | name | parent_id |
+----+-----------------------+-----------+
| 1 | Home | Null |
| 2 | Kitchen | 1 |
| 3 | Serving and reception | 2 |
| 4 | Spoon | 3 |
| 5 | Digital | NULL |
| 6 | Communication | 5 |
| 7 | Cellphone | 6 |
| .. | ... | ... |
+----+-----------------------+-----------+
在这种情况下,很难以正确的顺序获取所有嵌套相关项。我应该改变数据库结构吗?我的意思是,拥有这样一个数据模型的最佳方法是什么?
注意到,目前我使用 PHP 循环来获取相关标签并制作面包屑。另外,我使用 MySQL 版本
8.0.37
。
您可以像这样使用递归 CTE:
WITH RECURSIVE TagHierarchy AS (
SELECT id, name, parent_id name AS path
FROM tags
WHERE parent_id IS NULL
UNION ALL
SELET t.id, t.name, t.parent_id,
CONCAT(th.path, ' > ', t.name) AS path
FROM tags t
JOIN TagHierarchy th ON t.parent_id = th.id
)
SELECT id, name, path
FROM TagHierarchy
ORDER BY path;
结果
+----+-----------------------+----------------------------------+
| id | name | path |
+----+-----------------------+----------------------------------+
| 1 | Home | Home |
| 2 | Kitchen | Home > Kitchen |
| 3 | Serving and reception | Home > Kitchen > Serving and reception |
| 4 | Spoon | Home > Kitchen > Serving and reception > Spoon |
| 5 | Digital | Digital |
| 6 | Communication | Digital > Communication |
| 7 | Cellphone | Digital > Communication > Cellphone |
+----+-----------------------+----------------------------------+