[英]Trying to get the Parent ID of the Parent ID
I am working on an e-commerce site from scratch using PHP
and MYSQL
. 我正在使用
PHP
和MYSQL
从头开始在电子商务网站上工作。 I have one table for categories, with a column for ID
and a column for Parent_ID
. 我有一个表用于分类,其中一列用于
ID
,一列用于Parent_ID
。
When displaying the products on categories.php
, I have it set to display products where the Parent_ID
OR the ID
equals the $_GET['id']
field. 当显示的产品
categories.php
,我已经在这集展示产品Parent_ID
或ID
等于$_GET['id']
字段中。 But now I've run into a problem. 但是现在我遇到了一个问题。
In my "Groceries" category, I have the "Cleaning & Home" subcategory, and under "Cleaning & Home" I have several categories like "Laundry", "Bathroom Supplies", etc. 在“杂货”类别中,有“清洁和家庭”子类别,在“清洁及家庭”下,有几个类别,例如“洗衣”,“浴室用品”等。
My problem is that products in the third level don't display in the "Groceries" category, because technically the parent ID of "Laundry" is "Cleaning & Home". 我的问题是,第三级产品不会显示在“杂货”类别中,因为从技术上讲,“洗衣”的父ID是“清洁和家庭”。 There will never be more than three levels (Parent, child, grandchild), but I would like categories in the grandchild level to also display in the parent level.
永远不会超过三个级别(父,子,孙),但是我希望孙级别中的类别也显示在父级别中。
I've tried looking through MYSQL
documentation and on other forums but so far no luck. 我已经尝试过查看
MYSQL
文档和其他论坛,但到目前为止还没有运气。
This requires a couple of joins to get to the top parent: 这需要几个联接才能到达顶级父级:
select c.*,
coalesce(cp2.id, cp.id, p.id) as MostParentId
from categories c left outer join
categories cp
on c.parent_Id = cp.id left outer join
categories cp2
on cp.parent_id = cp2.parent_id
where c.id = $_GET['id'] or cp.id = $_GET['id'] or cp2.id = $_GET['id'];
You can then compare the id
s using or
for a match to the parent category, subcategory, or whatever. 然后,您可以使用
or
将其与父类别,子类别或其他内容进行匹配来比较id
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.