Silverstripe:如何获取父级 ProductCategory 及所有子孙分类中的 Product
解决方案
核心逻辑:先收集当前分类及所有子孙ProductCategory的ID,再匹配父ID在该范围内的产品。Silverstripe ORM的filter传入数组时会自动生成 IN查询,无需手动写SQL。
推荐实现(Silverstripe 4/5)
所有SiteTree子类默认携带Hierarchy扩展,内置递归获取后代节点的能力,无需手动实现递归:
public function Products() { // 范围包含当前分类自身ID $validCategoryIds = [$this->ID]; // 提取所有后代ProductCategory的ID并合并 $descendantIds = $this->getDescendants() ->filter('ClassName', ProductCategory::class) ->column('ID'); $validCategoryIds = array_merge($validCategoryIds, $descendantIds); return Product::get()->filter('ParentID', $validCategoryIds); }
该逻辑自动跟随内容阶段:前台仅返回已发布内容,后台可读取草稿,与原有单分类查询的权限逻辑一致。
全版本兼容写法
若使用Silverstripe 3.x等老版本,或需要自定义子分类过滤规则,可手动递归收集ID:
public function Products() { $validCategoryIds = array_merge( [$this->ID], $this->getDescendantCategoryIds($this->ID) ); return Product::get()->filter('ParentID', $validCategoryIds); } /** * 递归获取指定父ID下所有子孙分类的ID */ private function getDescendantCategoryIds(int $parentId): array { $ids = []; $childCategories = ProductCategory::get()->filter('ParentID', $parentId); foreach ($childCategories as $child) { $ids[] = $child->ID; $ids = array_merge($ids, $this->getDescendantCategoryIds($child->ID)); } return $ids; }
注意事项
- 两种写法均只会将
ProductCategory类型的节点纳入范围,分类下挂载其他类型页面不会干扰查询结果 - SiteTree默认已为
ParentID字段建立索引,常规业务量级无性能问题 - 若分类总量过千、层级极深,可将分类ID列表按顶级分类缓存,减少重复查询
内容的提问来源于stack exchange,提问作者Ivan
相关产品推荐
相关产品推荐

