Complexe filter in a collection

The question:

I would like to use addFieldToFilter (or other…) in a collection to make this filter :

(item1 = ‘value’ AND (item2 = ‘value1’ OR item = ‘value2’)) OR (item2 = ‘value3’ OR item = ‘value4’)

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Whenever dealing with complex filters, I prefer to work with the underlying Zend_Db_Select object. For example:

$collection
    ->getSelect()
    ->where(
        new Zend_Db_Expr("(item1 = '?' AND (item2 = '?' OR item = '?')) OR (item2 = '?' OR item = '?')"), 
        'value1', 
        'value2', 
        'value3', 
        'value4'
    );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment