分类db
id name parent_id slug
----------------------------------
1 Men 0 men
2 Shoes 1 shoes
3 Sports 2 sports
4 Women 0 women
5 Shoes 4 shoes
6 Sports 5 sports
假设我在domain/category/men/shoes/sports
$last_slug = end((explode('/', Request::url())));
在这里,我可以将sports
作为最后一次查询
问题:
如何检索所有父母slug 动态,所以如果slu depth = 3
我可以选择这样的东西?
SELECT t1.name AS level_one,
t2.name AS level_two,
t3.name AS level_three,
t3.id AS requested_id
FROM categories AS t1
LEFT JOIN categories AS t2 ON t2.parent_id = t1.id
LEFT JOIN categories AS t3 ON t3.parent_id = t2.id
WHERE t1.slug = 'men'
AND t2.slug = 'shoes'
AND t3.slug = 'sports'
LIMIT 1
答案 0 :(得分:2)
最好的方法是在其他列中存储完整路径。
这是在db - Materialized Path中存储树的标准方法之一。
作为奖励,您可以通过单个查询选择当前类别的所有子项。
当slug更改或子类别从一个父级移动到另一个父级时,正确更新路径会更加棘手。但这种行动不会经常发生。
使用连接动态构建查询对性能不利,尤其是对于这样一个简单的任务:按路径选择类别。
答案 1 :(得分:0)
只需在触摸周围交换连接顺序: -
SELECT t1.name AS level_one,
t2.name AS level_two,
t3.name AS level_three,
t1.id AS requested_id
FROM categories AS t1
LEFT JOIN categories AS t2 ON t2.id = t1.parent_id
LEFT JOIN categories AS t3 ON t3.id = t2.parent_id
WHERE t1.slug = 'sports'