【问题标题】:How to show only categories with products with CakePHP's tree behavioral?如何仅显示具有 CakePHP 树行为的产品类别?
【发布时间】:2011-07-05 07:55:22
【问题描述】:

我正在使用 CakePHP 的树形行为,需要知道类别中是否有任何产品或其子类别,因为我不想查看空类别。

我想做这样的事情:

$cat = $this->Category->find('first',array('conditions'=>array('id'=>$id)));
    $test = $this->Category->find('threaded', array(
        'conditions' => array(
            'Category.lft >=' => $cat['Category']['lft'], 
            'Category.rght <=' => $cat['Category']['rght'],
            'Product.InStock >'=>0 //NOT WORKING
        )
    ));

这将是取消设置不需要的数组维度的起点。在数据库中,分类有很多产品。

这个问题的最佳解决方案是什么?是否可以使用 category_id 避免 Product->find foreach 循环?

【问题讨论】:

    标签: php cakephp mptt


    【解决方案1】:

    未经测试

    $this->Category->Behaviors->attach->('Containable');
    
    $cat = $this->Category->find('first',array('conditions'=>array('id'=>$id)));
    
        $test = $this->Category->find('threaded', array(
            'conditions' => array(
                'Category.lft >=' => $cat['Category']['lft'], 
                'Category.rght <=' => $cat['Category']['rght']),
             // use containable behaviour and apply the condition
            'contain'=>array('Product'=>array('conditions'=>
                                              array('Product.InStock >'=> 0)
                                         )
                             )
            ));
    

    【讨论】:

    • 是的,它有效,谢谢!现在我只需要摆脱所有没有产品类别的“死胡同”。可能是多个 foreach 结构还是什么?
    • 我忘了在我的回答中提到,但如果你有成千上万的产品,这种查询和性能很容易失控。你会想要监控它,看看它是如何进行的。可能值得在contain 数组中使用fields 数组,并从Product 中仅选择您需要的字段并限制它/使用分页。
    • 谢谢,我一直在关注。加载时间现在约为 0.25 秒,而且它不是很高的流量站点,所以还没有关系。
    猜你喜欢
    • 2021-01-17
    • 2018-08-18
    • 2018-05-17
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多