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方法;这将以字符串形式返回idZend framework Magento:按类别获取产品集合时出错,zend-framework,magento,Zend Framework,Magento,我正在尝试使用类别过滤器获取产品集合,该过滤器将类别作为对象。问题是我遇到了以下错误: 致命错误:对中的非对象调用成员函数getId /var/www/vhosts/officeaccounts/subdomains/ls/httpdocs/app/code/core/Mage/Catalog/Model/Resource/Product/Collection.php 在线557 当我注释掉类别过滤器时,它不会得到错误 这是说我没有通过一个物体。但我仍然可以通过执行var_dump$catego
$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;
}
有什么想法吗?如果最后一个If-else功能块addAttributeToFilter of Mage\u Catalog\u Model\u Resource\u Product\u Collection,请尝试以下代码
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;
}
要按类别获取产品集合,请执行以下操作:
$category = Mage::getModel('catalog/category')->load(12);
$productCollection = $category->getProductCollection();
$productCollection->getSelect()->order(new Zend_Db_Expr('RAND()'));
print_r($productCollection->getData());
注意:此处12是类别id,您的代码存在一些问题: 如果当前类别不存在,则应注册该类别。 我在函数getFallbackItems的任何地方都看不到变量$category的声明,我想您正在遵循OOP编码。 因此,请确保在使用筛选器addCategoryFilter$类别时会出现错误 在使用变量之前,应始终检查其是否存在。 ==> 因此,代码可以改进如下:
$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;
}
在测试中,$category是由第一行Mage::registry还是由Mage::getModel行分配的?您使用的是哪个版本的Magento,因为在Enterprise 1.10.0.1中,错误列表中的文件不存在。让我假设它是一个新的1.6版本,使用了新的数据库抽象。这意味着你可能发现了一个bug。嗨,蒂姆,谢谢你的回复。是的,所以如果你通过搜索页面找到一个产品,这个代码在相关产品phtml上,那么当前的类别是未知的。因此,我正在做的是检查$category是否存在,如果不存在,我将通过获取它的一个父类来重置它。是的,马根托。1.6.0.0