Magento – Get Product collection with attribute value equal to null

magento-1.9product-collection

I have product attribute called 'category_3' with value 'kids' or null.i wanted only those products with an attribute 'category_3' value equals to null.my query is as follows:-

$products = Mage::getModel('catalog/category')->load(40)
            ->getProductCollection()
            ->addAttributeToSelect('*')
            ->addAttributeToFilter('status', 1)
            ->addAttributeToFilter('visibility', 4)
            ->setOrder('price', 'ASC');

i had tried following options and i am not getting the products with the category_3 value as null

// ->addAttributeToFilter('category_3',array('NULL' => true))
    //->addAttributeToFilter('category_3',array('eq'=>'NULL'))
    // ->addAttributeToFilter('category_3','')

Best Answer

Add your attribute to product collection using below code

<config>
    <frontend>
        <product>
            <collection>
                <attributes>
                    <category_3 />
                </attributes>
            </collection>
        </product>
    </frontend>
</config>

after adding attribute to collection using below code you can filter collection

$products = Mage::getModel('catalog/category')->load(40)
            ->getProductCollection()
            ->addAttributeToSelect('*')
            ->addAttributeToFilter('category_3',array('null' => true))
            ->addAttributeToFilter('status', 1)
            ->addAttributeToFilter('visibility', 4)
            ->setOrder('price', 'ASC');