dpw5865 2013-07-12 14:50
浏览 23
已采纳

如何从url中查找slug名称并创建动态查询语句

Categories 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

Let's say i'm on domain/category/men/shoes/sports

$last_slug = end((explode('/', Request::url()))); 

Here I'll can get sports as last query

Question :

How to retrieve all parents slug dynamically, so I can select something like this if the slug 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 
  • 写回答

2条回答 默认 最新

  • douheng8629 2013-07-12 15:03
    关注

    The best way will be to have an additional column where you will store the complete path.

    This is one of the standard ways of storing trees in db - Materialized Path.

    As a bonus, you will have the ability to select all children of the current category with a single query.

    It makes it a bit more tricky to correctly update paths when slugs are changed or subcategories are moved from one parent to another. But this are actions that will be performed not very often.

    Dynamically building the query with joins is bad for performance, especially for such a simple task: select category by path.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效