I am trying to add multiple filters to a magento collection which I can do on a basic level. What I really want to do is to be able to filter a collection by a number of nested filters which could be any level deep. For example i know I can add mutiple filters using code like:
$collection->addAttributeToFilter('example_attribute', array('eq' => 1));
What I want to be able to do is to have filters (AND & OR) that can be nested within each other. I am not sure if Magento collection allow you to do this already but I have not been able to find any examples online.
To give further detail and example: I would need to filter a collection where the equivalent SQL (ignore the selected fields I need and the JOINS) would be:
SELECT .........
WHERE
(attribute1 = 1
OR
atttribute2 = 'yes')
AND
qty > 5
AND(
(attribute3 != 'no'
AND
attribute4 = 50 )
OR
(attribute3 != 'no'
AND
attribute6 > 50 )
)
This is just a quick crude example but the basic problem is how to nest any number of filters.
You can use OR conditioning using code like this:
$collection->addAttributeToFilter(array(
array('attribute'=> 'someattribute','like' => 'value'),
array('attribute'=> 'otherattribute','like' => 'value'),
array('attribute'=> 'anotherattribute','like' => 'value'),
));
Edit: Using this you should be able to do at least AND and OR conditioning in a query. It seems that the standard behavior does not allow for a nested AND OR conditioning. So I assume you would need to write a custom query for that. For further reference, check the file Mage_Eav_Model_Entity_Collection_Abstract in which the method addAttributeToFilter is defined.