Magento:按类别收集产品时出错

时间:2011-11-09 12:59:51

标签: zend-framework magento

我正在尝试使用类别过滤器获取产品集合,该过滤器将类别作为对象。问题是我收到以下错误:

  

致命错误:在非对象中调用成员函数getId()   /var/www/vhosts/officeaccounts/subdomains/ls/httpdocs/app/code/core/Mage/Catalog/Model/Resource/Product/Collection.php   在第557行

当我注释掉类别过滤器时,它不会出错。

它说我不是在传递一个物体。但是我仍然可以通过执行var_dump($category->getId());来访问对象的getId()方法。这会将id作为字符串返回。

$category = Mage::registry('current_category');
if (!$category) {
    $product = $this->getProduct();
    $cats = $product->getCategoryIds();
    $category = Mage::getModel('catalog/category')->load($cats[0]);
}

function getFallbackItems() {
    $productCollection = Mage::getResourceModel('catalog/product_collection')
                    ->addAttributeToSelect('*')
                    ->addCategoryFilter($category);
    $productCollection->getSelect()->order(new Zend_Db_Expr('RAND()'));
    return $productCollection;
}

任何想法?

3 个答案:

答案 0 :(得分:0)

如果Mage_Catalog_Model_Resource_Product_Collection的函数addAttributeToFilter()的最后一个if else块尝试此代码

    elseif(is_string($attribute) && $attribute == 'category_ids'){

        if(isset($condition['eq'])){
            $this->getSelect()->join(
            array('category' => $this->getTable('catalog/category_product')),
            'category.product_id=e.entity_id AND category.category_id='.$condition['eq'],
            array()
            );
        }
        return $this;

    } 

答案 1 :(得分:0)

要按类别获取产品集,请执行以下操作:

$category = Mage::getModel('catalog/category')->load(12);
$productCollection = $category->getProductCollection();
$productCollection->getSelect()->order(new Zend_Db_Expr('RAND()'));
print_r($productCollection->getData());

注意:这里 12 是category_id

答案 2 :(得分:0)

您的代码存在一些问题:

  1. 您应该注册类别(current_category),以防它不存在。
  2. 我没有在函数getFallbackItems中看到变量$ category的声明(我想你正在遵循OOP编码)。 因此,请确保在使用过滤器addCategoryFilter($ category)
  3. 时出现错误
  4. 在使用之前,您应该始终检查变量是否存在。
  5. ====>

    所以代码可以改进如下:

    $category = Mage::registry('current_category');
    
    if (!$category) {
        $product = $this->getProduct();
        $cats = $product->getCategoryIds();
        $category = Mage::getModel('catalog/category')->load($cats[0]);
        Mage:register('current_category', $category);
    }
    
    // Suppose it will be called somewhere
    function getFallbackItems() {
        $category = Mage::registry('current_category');
        $productCollection = Mage::getResourceModel('catalog/product_collection')
            ->addAttributeToSelect('*');
    
        if ($category && $category->getId()) {
            $productCollection->addCategoryFilter($category);
        }
    
        $productCollection->getSelect()->order(new Zend_Db_Expr('RAND()'));
    
        return $productCollection;
    }
    
相关问题