Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why isn't it showing all descendant categories in breadcrumbs?

When searching by product category, I need to display all of its parent categories.

When there are multiple levels, it only displays two results.

CREATE TABLE `category` (
  `id` int NOT NULL,
  `parent_category_id` int,
  `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB;

INSERT INTO `category` (`id`, `parent_category_id`, `name`) VALUES
(1, NULL, 'Male'),
(2, 1, 'T-shirts'),
(3, 1, 'Shoes'),
(4, 2, 'Tank top'),
(5, 2, 'Basic shirts');

SELECT CONCAT(t1.name, ' > ', t2.name) as breadcrumb
FROM category AS t1
LEFT JOIN category AS t2 ON t2.parent_category_id = t1.id
WHERE t2.id = 4; #( 4 or 5 )

Result: T-shirts > Tank top

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected outcome: Male > T-shirts > Tank top

Does not display the "Male" category

>Solution :

Well, you only join one level. If you want to join arbitrary levels, you can use a recursive CTE.

WITH RECURSIVE
breadcrumbs
AS
(
SELECT 1 AS ordinality,
       c.name,
       c.subcategory_id
       FROM category AS c
       WHERE c.id = 4
UNION ALL
SELECT bc.ordinality + 1 AS ordinality,
       c.name,
       c.subcategory_id
       FROM breadcrumbs AS bc
            INNER JOIN category AS c
                       ON c.id = bc.subcategory_id
)
SELECT group_concat(bc.name
                    ORDER BY bc.ordinality DESC
                    SEPARATOR ' > ') AS breadcrumb
       FROM breadcrumbs AS bc;

db<>fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading