cancel
Showing results for 
Search instead for 
Did you mean: 

How to get parent category id using product id - mysql?

How to get parent category id using product id - mysql?

How to get parent category id,


Books/Spiritual Books/Boys

Books -> 5 [id]

Spiritual Books -> 18[id]

Boys -> 78[id]


How to get parent category id using product id using mysql, here Books is parent category.

Note : My product assigned Boys category only.

1 REPLY 1

Re: How to get parent category id using product id - mysql?

To get the parent category ID of a product in MySQL, you can use the following query:

SELECT c.parent_id
FROM catalog_category_product AS cp
INNER JOIN catalog_category AS c ON cp.category_id = c.entity_id
WHERE cp.product_id = [PRODUCT_ID]
AND c.parent_id != 0
ORDER BY c.level DESC
LIMIT 1

Replace [PRODUCT_ID] with the actual ID of your product. This query will return the ID of the top-level parent category of the product, in this case, 5 for the "Books" category.

 

Note that this assumes that your category tree has only one level of parent categories. If you have a more complex category structure with multiple levels of parent categories, you may need to modify the query accordingly.