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
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
How can this be achieved in magento2?
ReplyDeleteThe 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..
ReplyDeletemagento development company in bangalore