Magento 1 – Use of addExpressionFieldToSelect vs addFieldToSelect

collection;magento-1

I'm studying Magento and I don't really understand what is the use of addExpressionFieldToSelect over addFieldToSelect? I haven't found the answer anywhere in my reading. As far as I can tell, it seems to be rewriting field names–but only if you pass in an array with the rewrite. Why couldn't you just do this with addFieldToSelect in the first place, if you know what the field should be rewritten as?

Best Answer

In addExpressionFieldToSelect(), you can pass a Zend_Db_Expr instance with an arbitrary SQL expression.

So for example, this is possible with addExpressionFieldToSelect(), but not with addFieldToSelect():

$collection->addExpressionFieldToSelect(
    'name_in_upper_case',
    new Zend_Db_Expr('UPPER(name)'),
    []
);

and results in an SQL query with

SELECT UPPER(name) as name_in_upper_case FROM ...

The placeholders for fieldnames are just syntactic sugar on top.