3

I am retrieving a product collection and filtering the list by category.

I have just had to add some sub categories to one of them and now the products in the sub-categories are appearing in the collection for the parent category and I cannot work out how to only show products directly assigned to the parent category.

Here is an example of the code:

$cat = Mage::getModel("[custom-namepace]/Categories"); //this just extends the native Categories model
$cat->load($catId);  //some number
$products = Mage::getResourceModel("catalog/product_collection")
                ->setStoreId(Mage::app()->getStore()->getId())
                ->addUrlRewrite()  
                ->addCategoryFilter($cat)
                ->setOrder("name","asc");

I am unable to add a filter on category_id as that causes an error. I have tried:

->addAttributeToFilter("category_id",$cat->getId())

and

->addAttributeToFilter("category_id",array("eq"=>$cat->getId()))

and

->addAttributeToFilter("category_id",array("in"=>$cat->getId()))

These all throw a fatal error like.

Fatal error: Call to a member function getBackend() on a non-object in [...]\app\code\core\Mage\Eav\Model\Entity\Abstract.php on line 816

Any pointers on how to avoid picking up products in child categories?

UPDATE

I have now also tried to get the products list through the category and I still get products from the child categories.

$products = $cat->getProductCollection()
                ->addAttributeToSelect("name")
                ->addUrlRewrite()
                ->setOrder("name","asc");
3
  • Well I'm pretty this would only work for native category models. As you're using a adamequip_aepage/Categories model I doubt it'll work. Jul 15, 2016 at 10:36
  • well it gets the products fine when a category has no children - the custom (now removed project reference, perhaps you could, thanks) Categories model just extends the native category model Jul 15, 2016 at 10:46
  • I have modifed my code to use directly the native catalog/category model and the problem still occurs - the product collection still contains products from the child categories Jul 15, 2016 at 10:54

1 Answer 1

1

you could do something like this:

$collection = Mage::getResourceModel('catalog/product_collection')
->joinField('category_id',
    'catalog/category_product',
    'category_id',
    'product_id = entity_id',
    null)
->addFieldToFilter('category_id', 3);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.