【问题标题】:Magento - addCategoryFilter throws an errorMagento - addCategoryFilter 抛出错误
【发布时间】:2011-02-19 15:46:42
【问题描述】:

我已成功运行此查询:

 $_productCollection = Mage::getResourceModel('reports/product_collection')
                        ->addAttributeToSelect('*')
                        ->setOrder('created_at', 'desc')
                        ->setPage(1, 5);

但是当我添加时

->addCategoryFilter('3')

我收到以下错误:

Fatal error: Call to a member function getId() on a non-object in /home/sitename/public_html/app/code/core/Mage/Catalog/Model/Resource/Eav/Mysql4/Product/Collection.php on line 556

它运行的块定义为

<block type="catalog/product_list" name="catalog.right.bestsellers" template="catalog/navigation/right.phtml"/>

在目录.xml

【问题讨论】:

    标签: magento magento-1.4


    【解决方案1】:

    这涵盖了 1.4.2。根据您的错误,我认为您运行的是稍旧的版本,但您的错误的根本原因应该是相同的。

    类别名reports/product_collection解析为

    Mage_Reports_Model_Mysql4_Product_Collection
    

    在资源模式上下文中。 Mage_Reports_Model_Mysql4_Product_Collection 类是 Mage_Catalog_Model_Resource_Eav_Mysql4_Collection_Abstract 的子类。 Mage_Catalog_Model_Resource_Eav_Mysql4_Collection_Abstract 上的 addCategoryFilter 看起来像这样

    public function addCategoryFilter(Mage_Catalog_Model_Category $category)
    {
        $this->_productLimitationFilters['category_id'] = $category->getId();
        if ($category->getIsAnchor()) {
            unset($this->_productLimitationFilters['category_is_anchor']);
        }
        else {
            $this->_productLimitationFilters['category_is_anchor'] = 1;
        }
    
        ($this->getStoreId() == 0)? $this->_applyZeroStoreProductLimitations() : $this->_applyProductLimitations();
    
        return $this;
    }
    

    请注意,在 1.4.2 中,参数中正在进行一些类型检查

    public function addCategoryFilter(Mage_Catalog_Model_Category $category)
    

    我怀疑你的版本没有那个检查。因此,到达时失败

    $this->_productLimitationFilters['category_id'] = $category->getId();
    

    您传入一个字符串,然后 Magento 尝试在该字符串上调用 getId。这就是你得到错误的原因。

    Magento 希望您传入一个类别对象,而不是类别 ID。试试这个

    $category = Mage::getModel('catalog/category')->load(3);
    $p = Mage::getResourceModel('reports/product_collection')
                ->addAttributeToSelect('*')
                ->setOrder('created_at', 'desc')
                ->addCategoryFilter($category)
                ->setPage(1, 5);
    

    【讨论】:

    • 我们如何从多个类别中获取产品?这个“addCategoryFilter()”只会占用 1 个类别。
    【解决方案2】:

    addCategoryFilter() 的参数必须是 Mage_Catalog_Model_Category 类型的对象。

    【讨论】:

      猜你喜欢
      • 2014-02-24
      • 2016-04-26
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      • 2012-10-28
      • 1970-01-01
      相关资源
      最近更新 更多