简体   繁体   English

无法获取给定类别的产品集合

[英]Failing to fetch product collection for a given category

I've written a method that I'm calling from my list.phtml file. 我编写了一个从list.phtml文件调用的方法。 The logic should simply output the number of products in the currently viewed category and the highest and lowest prices. 该逻辑应仅输出当前查看类别中的产品数量以及最高和最低价格。 Pretty straight forward really. 真的很简单。

For reasons beyond my understanding it's always returning that the current category contains no products, and I can't figure out why but I presume it's because I'm not fetching the product collection correctly. 由于超出我的理解范围的原因,总是会返回当前类别不包含任何产品的信息,我无法弄清楚原因,但我想是因为我没有正确获取产品集合。

Here's the code for my method. 这是我的方法的代码。

    public function writeCatInfo(){
       if(Mage::registry('current_category')){
            $_productCollection=$this->getLoadedProductCollection;
            $catname = Mage::registry('current_category')->getName();
            $priceArray = array();
            foreach ($_productCollection as $_product){
                $priceArray[] = $_product->getSpecialPrice();
            }
            $numItems = count($_productCollection);
            $highPrice = number_format(max($priceArray),2);
            $lowPrice = number_format(min($priceArray),2);
            $infostring =  ucwords($catname)." contains ".$numItems." products with prices ranging from £".$lowPrice." to £".$highPrice;
            echo $infostring;
        }   
    }

this will help you to get current category product collection. 这将帮助您获取当前类别的产品系列。

$category_id = Mage::getModel('catalog/layer')->getCurrentCategory()->getId();
$category = Mage::getModel('catalog/category')->load($category_id);
$products = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addCategoryFilter($category)
    ->setOrder('price', 'ASC')
    ->load();

Turns out my helper was extending the wrong class - Mage_Core_Helper_Abtract instead of Mage_Catalog_Block_Product_List . 原来我的助手正在伸出了错误的类- Mage_Core_Helper_Abtract代替Mage_Catalog_Block_Product_List Changing this fixed the problem. 更改此选项可解决问题。

Please see the below code to get product collection by Category id 请查看以下代码,以按类别ID获取产品集合

$products = Mage::getModel('catalog/category')->load($category_id) $ products = Mage :: getModel('catalog / category')-> load($ category_id)

->getProductCollection() -> getProductCollection()

->addAttributeToSelect('*') // add all attributes - optional -> addAttributeToSelect('*')//添加所有属性-可选

->addAttributeToFilter('status', 1) // enabled -> addAttributeToFilter('status',1)//启用

->addAttributeToFilter('visibility', 4) //visibility in catalog,search -> addAttributeToFilter('visibility',4)//在目录中可见,搜索

->setOrder('price', 'ASC'); -> setOrder('price','ASC'); //sets the order by price //按价格设置订单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM