Thursday, August 9, 2012

Using IF-ELSE OR CASE-WHEN in Magento Collection - Expression based field by addExpressionAttributeToSelect

Using IF-ELSE OR CASE-WHEN  in Magento Collection - Expression based temporary column field  by addExpressionAttributeToSelect

Magento addExpressionAttributeToSelect  method can be used to create temporary column in
collections

$_collection Mage::getResourceModel('sales/order_collection')
        ->
addExpressionAttributeToSelect('your_temp_column''CASE order_id WHEN 1 THEN one ELSE TWO END ''');

on printing sql query using getselect
echo $_collection->getSelect() ;


 the magento will create query something like this  SELECT (CASE order_id WHEN 1 THEN one ELSE TWO END) AS your_temp_column

The temproary column can be used for sorting and filtering also , please note for filtering
you need to use 'having'  instead of builtin addAttributeToFilter method.
$_collection->getSelect()->having('your_temp_column = "one" '); 

hope this helps




2 comments:

  1. How can this be achieved in magento2?

    ReplyDelete
  2. The blog was absolutely fantastic! Lot of great information which can be helpful in some or the other way. Keep updating the blog, looking forward for more contents...Great job, keep it up..
    magento development company in bangalore 

    ReplyDelete