Sam Stones
Sam Stones

Reputation: 73

How to filter Magento collection for a date or null

I have some Magento code that I'm trying to use to filter a collection of products. I want to find all products where the date is BEFORE a certain date OR the date hasn't been set (ie is null).

I have:

function getProduct($product_id) {
	global $proxy, $sessionId, $conn, $start_date, $time_to_run;
	if ($product_id == 'all') {
		$result=Mage::getModel("catalog/product")
		  ->getCollection()
		  ->addAttributeToSelect('*')
                  ->addAttributeToFilter('price_adjust_active', array('null' => true))
		  ->addAttributeToFilter('price_adjust_active', '1')
		  ->addAttributeToFilter(array(
        array('attribute'=> 'price_adjust_last_run','lt' => date('Y-m-d H:i:s', $time_to_run)),
        array('attribute'=> 'price_adjust_last_run', 'null' => true)
    ))
		  ->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED))      
		  ->setOrder('entity_id', 'DESC')
		  ->setPageSize(1);
    } else {
    	
		$result=Mage::getModel("catalog/product")
		  ->getCollection()
		  ->addAttributeToSelect('*')
		  ->addAttributeToFilter('entity_id', array('eq' => $product_id))
                  ->addAttributeToFilter('price_adjust_active', array('null' => true))
		  ->addAttributeToFilter('price_adjust_active', '1')
		  ->addAttributeToFilter(array(
        array('attribute'=> 'price_adjust_last_run','lt' => date('Y-m-d H:i:s', $time_to_run)),
        array('attribute'=> 'price_adjust_last_run', 'null' => true)
    ))
		  ->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED))      
		  ->setOrder('entity_id', 'DESC')
		  ->setPageSize(1);
	}	

and I can successfully filter out the products with the dates set before my specified date. I just can't get the "null" attribute to work. As you can see from my code, I have 2 different filters in there, and neither of them seem to give me the desired results.

The two faulty attempts are:

->addAttributeToFilter('price_adjust_active', array('null' => true))

or

array('attribute'=> 'price_adjust_last_run', 'null' => true)

Upvotes: 1

Views: 2939

Answers (1)

Scruffy Paws
Scruffy Paws

Reputation: 1250

Magento has a special way to filter dates instead of just using a straight greater or less than.

Try this...

->addAttributeToFilter('price_adjust_last_run', array('or'=> array(
    0 => array(
        'date' => true,
        'from' => date('Y-m-d H:i:s', $time_to_run - 1)
    ),
    1 => array('is' => new Zend_Db_Expr('null')))
), 'left')

You are setting date to true and then you'll probably want to make sure to subtract 1 second from your $time_to_run variable.

This works similarly with addFieldToFilter() as well.

Upvotes: 2

Related Questions