问题描述
|
我有一个正在做的购物车。我很困惑,无法找到如何在属于我所关注类别的多级类别中加载产品。
例如:
-汽车
Subarus(传统,内陆)-Holden(加莫斯,科莫多)-Toyota(花冠,凯美瑞)
如果我正在寻找汽车类别,则可以选择子类别,但无法查看这些子类别中的实际产品。有什么办法可以做到吗?即使您可以具有无限级别的类别,例如\“ ROOT> Cars> Sedan> Subaru's ... \”?
每个产品都有一个与类别相关的类别ID。每个类别都有其唯一的ID和一个\'parent \'ID,该ID具有其所属子类别的ID。
解决方法
我认为您需要做的是建立类别ID列表,然后为您的sql构造一个
IN
子句。假设您具有以下类别结构:
汽车(id:1)
丰田(ID:2,父母:1)
迷你(ID:3,父母:2)
花冠(id:4,父母:3)
霍尔顿(ID:5,父母:1)
运动(id:6,父母:5)
HSV(id:7,parent:6)
要获取某个类别的所有后代,您需要使用以下类似内容遍历父/子结构:
/**
* I\'m only writing pseudocode here btw; I haven\'t tested it.
* Obviously you\'ll need to fire the SQL commands...
*/
function getKids ($id,$found = array())
{
array_push ($found,$id);
$nbrKids = \"select count(id) from category where parent_id = $id\";
if ($nbrKids > 0) {
$newKids = \"select id from category where parent_id = $id\";
foreach ($newKids as $kid) {
return getKids ($kid,$found);
}
}
else {
return $found;
}
}
然后像这样调用getKids()
,其中$id
是您的类别ID:
$ids = getKids($id);
$ids
是您感兴趣的所有类别的数组。然后,您可以使用join()
构造一个SQL字符串:
$sql = \"select * from cars where category_id in (\" . join (\",\",$ids) . \")\";
为了正确起见,您应该检查$ids
首先至少有1个成员,否则您的SQL查询将无效。
[编辑:实际上,在上面的代码中,“ 5”将始终至少具有一个成员:初始ID。但是,代码无法验证初始ID是否为有效的category_id。 ]