我有以下代码,显示当前类别中的5种产品(类别为cat:63):
$_helper = $this->helper('catalog/output');
$_category = $this->getCurrentCategory();
$collection = $_category->getProductCollection();
Mage::getModel('catalog/layer')->prepareProductCollection($collection);
$numProducts = 5;
$collection->setPage(1, $numProducts)->load();
这工作正常,但我想进一步调整,因此它只显示在另一个类别(产品目录ID:71)中也找到的产品,$collection->addCategoryFilter(71);
但是当我这样做时,我得到了错误:
Fatal error: Call to a member function getId() on a non-object in
完整的代码是:
$_helper = $this->helper('catalog/output');
$_category = $this->getCurrentCategory();
$collection = $_category->getProductCollection();
Mage::getModel('catalog/layer')->prepareProductCollection($collection);
// this line throws the error
$collection->addCategoryFilter(71);
$numProducts = 5;
$collection->setPage(1, $numProducts)->load();
foreach($collection as $_product){
// output products...
};
这行是不正确的
$collection->addCategoryFilter(71);
我猜您正在尝试过滤ID = 71的类别。对吗?如果是这样,您可以按照以下方式进行操作:
$catToFilter = Mage::getModel('catalog/category')->load(71);
$collection->addCategoryFilter($catToFilter);
出现问题的原因是,当类别过滤器方法需要一个对象时,您正在提供ID。因此,您将获得ID为71的类别对象,并将其作为参数传递。
================================================== ===============================
更新:仅显示两个类别中共有的产品。
// 1st category
$cat1 = Mage::getModel ('catalog/category')->load(63);
//2nd category
$cat2 = Mage::getModel ('catalog/category')->load(71);
//loading cat2 products
$collection = $cat2->getProductCollection();
//this keeps the common products and remaining products of cat1
$collection->addCategoryFilter($cat1);
$removeList = array();
foreach ($collection as $prod)
{
$prodCatIds = $prod->getCategoryIds();
//if the current collection products does not lie in cat2
if (! in_array($cat2->getId(), $prodCatIds))
{
//creating a list of product ids that are not common
array_push($removeList , $prod->getId());
}
}
//removing the UNCOMMON products from the collection
foreach($removeList as $rl)
$collection->addAttributeToFilter('entity_id', array('neq' => $rl)) ;
//The collection is now ready
foreach($collection->getData() as $_product){
//$_product details or load product object
zend_debug::dump($_product['sku']);
}
有点肮脏的方法,但希望对您有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句