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条)

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题