【问题标题】:cakephp 2.2 tree behaviour - Count the products in the given category and all subchildren recursivelycakephp 2.2 树行为 - 递归计算给定类别中的产品和所有子子项
【发布时间】:2013-03-07 08:37:10
【问题描述】:

CakePHP 2.2

我使用树行为为我的类别构建了一个嵌套的垂直菜单。在这些类别中有产品。我想要实现的是类别名称旁边包含指定类别中的产品数量。这是一个例子:

Automobile (100) > SUV (35)
                 > Pickup (25)
                 > Berline (40)

在类别旁边,我们可以看到其中的产品数量。

我在网上查了一下,找到了这个教程:http://mrphp.com.au/blog/fun-tree-behaviour-cakephp 在“查找您的数据”最后一部分中有一行说明了如何实现这一目标:

 // count the posts in the given category and all subchildren recursively
        $id = 123;
        $postCount = $this->Category->postCount($id); 
        debug($postCount); 

此代码中的问题是它使用 postCount() 但在我的情况下,我的类别没有帖子而是产品,换句话说,我使用 Product 模型和 ProductsController,因此它无法工作。我能做到吗?

[编辑]

我找到了解决方案。首先,我在类别表中创建了一个新字段并将其命名为 product_count(关联表的单数名称)。然后我在我的 ProductsController.php 中添加了一个 belongsTo。如下:

public $belongsTo = array(
        'Category' => array(
            'counterCache' => true
            )
        );

最后在我的垂直菜单的 foreach 中,我只是在类别名称旁边添加了这个:

$v['Category']['product_count']

现在可以了!

【问题讨论】:

  • 那为什么不相应地“重命名”它呢?
  • 谢谢马克,我不明白你的意思。你能说得更具体点吗?

标签: cakephp


【解决方案1】:

将 postCount 函数替换为:

function productCount($id, $direct=false){
    if (!$direct) {
        $ids = array($id);
        $children = $this->children($id);
        foreach ($children as $child) {
            $ids[] = $child['Category']['id'];
        }
        $id = $ids;
    }
    $this->Product->recursive = -1;
    return $this->Product->findCount(array('category_id'=>$id));
}

【讨论】:

  • 嗨,马特,感谢您的关注。我试图包含您的代码,但作为初学者,我无法使其工作。我回答了我自己的问题以展示我的一些代码,看看我如何使用你的代码。再次感谢
猜你喜欢
  • 2017-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
  • 1970-01-01
  • 2021-01-11
  • 1970-01-01
相关资源
最近更新 更多