具有一个数据的SilverStripe GroupedList

具有一个数据的SilverStripe GroupedList,silverstripe,Silverstripe,我在绞尽脑汁想弄明白,我觉得我想得太多了 因此,我构建了2个数据对象(品牌、产品)和1个控制器/页面(产品类型) ProductType有许多产品 产品有一个品牌 产品有一个ProductType 品牌有很多产品 我想做的是: ProductType页面应提供仅由该类型产品使用的品牌列表 现在,我有一个工作,但它感觉黑客和不是很便携。示例如下: ProductType控制器: public function getBrands() { if($products = $thi

我在绞尽脑汁想弄明白,我觉得我想得太多了

因此,我构建了2个数据对象(品牌、产品)和1个控制器/页面(产品类型)

  • ProductType有许多产品
  • 产品有一个品牌
  • 产品有一个ProductType
  • 品牌有很多产品
我想做的是:

ProductType页面应提供仅由该类型产品使用的品牌列表

现在,我有一个工作,但它感觉黑客和不是很便携。示例如下:

ProductType控制器:

public function getBrands() {

        if($products = $this->Products()) {
            $group = GroupedList::create($products->sort('BrandID'))->GroupedBy('BrandID');
        }

    }
产品类型模板:

<% if Brands %>
    <ul>
        <li><a href="{$Link}">All</a></li>
        <% loop Brands %>
            <% loop Children.Limit(1) %>
                <li><a href="{$Top.Link}brand/{$Brand.URLSegment}">$Brand.Title</a></li>
            <% end_loop %>
        <% end_loop %>
    </ul>
<% end_if %>

是否有一种方法可以在ProductType控制器中构建一个方法,该方法只返回该类型产品使用的品牌的数据列表

使用Silverstripe 3.1.3


如果我需要更清楚一些事情,请告诉我,谢谢

啊,我猜你对分组列表有误解

您已经拥有此产品类型的所有产品的数据列表

这是有很多关系的

$this->Products()

现在,您需要按BrandID对当前产品进行分组。您的方法命名可能会混淆,因此让我们稍微重命名一下:

public function getProductsGroupedByBrands() {

    if($products = $this->Products()) {
        $group = GroupedList::create($products->sort('BrandID'))
            ->GroupedBy('BrandID');
    }

}
因此,在模板中有一个GroupedList,可以循环使用

<% if Products %>
    <ul>
        <li><a href="{$Link}">All</a></li>
        <% loop ProductsGroupedByBrands %>
            <li>
                <%-- here you should be able to see the grouping relation --%>
                <a href="{$Top.Link}brand/{$Brand.URLSegment}">$Brand.Title</a>


                <%-- in doubt use the First element to get the current Brand, it's a has_one -->
                <% with $Children.First %>
                    <a href="{$Top.Link}brand/{$Brand.URLSegment}">$Brand.Title</a>
                <% end_with %>
                <ul>

                <% loop Children %>
                <%-- here are the products grouped by brand --%>
                    <li>$Title</li>
                <% end_loop %>
                </ul>
            </li>
        <% end_loop %>
    </ul>
<% end_if %>


  • 通常,它应该只按使用int$this->Products()的品牌进行分组;那有什么问题?你有所有品牌的名单吗?或$this->products()中该产品未使用的品牌?您是否仔细检查了后者并检查了您的数据库?顺便说一句:你用的是哪个版本的SS?非常感谢wmk的回复!这里有两件事:$Brand在ProductsGroupedByBrands方法的顶部不可用。您只能返回用于对组进行排序的内容(在本例中为BrandID)$品牌只有在孩子们之间循环才能进入。此外,这与我做这件事的方式基本相同,我在控制器内部寻找一种解决方案,使其更具可移植性(即:ProductType中使用的品牌数据列表)$Brand.Title应该在列表中起作用,因为它就像“仅在第一项上循环”(嗯,类似于此)