如何解决Silverstripe - 显示来自父类别和子类别的产品
当我尝试从父类别及其子类别循环所有产品时遇到问题。
我创建了两种额外的页面类型:
- 产品类别
- 产品
在 SiteTree
(页面)中,我创建了结构:
|-Pages
|- Dental equipment (productCategory)
|----- Sub category (productCategory)
|----- Sub sub category (productCategory)
|----- Sub sub sub category (productCategory)
|----- Product 1 (product type)
|----- Product 2 (product type)
|----- Product 3 (product type)
|----- Product 4 (product type)
现在在 ProductCategory_Controller
中,我创建了循环所有不工作的产品的方法。
public function Products()
{
$products = Product::get()->filter([
'ParentID' => $this->ID
]);
return $products;
}
我的问题是如何获取属于所有parenet和子类别的所有产品?
解决方法
如果您正在尝试获取当前类别页面和所有父类别页面的产品,那么下面的示例代码可能会为您指明正确的方向。
如果我误解了您的问题,请发表评论,我会更新我的答案。
<?php
namespace {
class ProductCategoryPageController extends PageController
{
public function ProductsInCurrentPageTree()
{
$currentPage = $this->data();
$parentPage = $currentPage->getParent();
if (!$parentPage) {
// No parent page,return the current page products
return ProductPage::get()->filter('ParentID',$currentPage->ID);
}
$pageTreeIds = [
$currentPage->ID,$parentPage->ID,];
while ($parentPage = $parentPage->getParent()) {
// Any conditions to break out of the loop,for instance,if your category/product pages does not start from the root level
if (!$parentPage instanceof ProductCategoryPage) {
break;
}
$pageTreeIds[] = $parentPage->ID;
}
return ProductPage::get()->filterAny(['ParentID' => $pageTreeIds]);
}
}
}
,
对子类别页面递归调用相同的函数,但当没有子类别时,则将产品添加到数组列表中。未经测试的代码,但应该足够清楚:
class ProductCategoryPageController extends PageController {
public function ProductsRecursive($iParentID,$productList) {
$productCategoryPages = ProductCategoryPage::get()->filter(['ParentID' => $iParentID]);
if ($productCategoryPages) {
//assuming product category pages only have children and no products themselves
foreach ($productCategoryPages as $productCategoryPage)
$productList = $this->ProductsRecursive($productCategoryPage->ID,$productList);
}
else {
//assuming you only are collecting product pages that have no children
foreach (ProductPage::get()->filter(['ParentID' => $iParentID]) as $productPage)
$productList->push($productPage);
}
return $productList;
}
public function Products() {
return $this->ProductsRecursive($this->ID,ArrayList::create());
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。