Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento Product Collection Get Only Products From Certain Categories

Tags:

php

magento

I am trying to get a list of products that have a sale price that are only in certain categories. Right now I am trying to use a product collection to get this data. I am not sure how I would go about restricting the collection for particular categories only. Here is what I have so far:

$products = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('status', 1)
    ->addAttributeToFilter('visibility', 4)
    ->addAttributeToFilter('special_price', array('neq' => ""))
    ->addAttributeToFilter('discontinued', array('neq' => 1))
    ->setPageSize(10)
    ->setOrder('price', 'ASC')
    ;

The discontinued attribute is a custom attribute that we use so that products don't display but also don't 404.

Is there a way to use the product model and restrict to certain categories?

like image 521
Josh Pennington Avatar asked Feb 08 '11 17:02

Josh Pennington


1 Answers

Figured it out. You start with the category and get the product collection from the category and then refine it down from there. In code it looks like this:

$products = Mage::getModel('catalog/category')->load(410)
    ->getProductCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('status', 1)
    ->addAttributeToFilter('visibility', 4)
    ->addAttributeToFilter('special_price', array('neq' => ""))
    ->addAttributeToFilter('discontinued', array('neq' => 1))
    ->setOrder('price', 'ASC')
    ;
like image 148
Josh Pennington Avatar answered Oct 22 '22 14:10

Josh Pennington