I'm adding a couple of filters with addAttributeToFilter
. I have the fields "year", "year_from", "year_to". I either want to match the year exactly to the "year" attribute or make a "between" by using "year_from" and "year_to". I know how to use addAttributeToFilter
to make "OR" conditions. However
I don't know how to make an "OR" filter with a grouped "AND", something like year = 1999 OR (year_from <= 1999 AND year_to >= 1999)
.
3 Answers
You can do it as -
$filter_a = array('eq'=>'1999');
$filter_b = array('from'=>'1999','to'=>'1999');
addFieldToFilter('year',array( $filter_a, $filter_b));
-
The from/to filter is not applied to the same attribute but to different ones - year_from, year_to. This is because the vendors provide different information for different products - sometimes a specific year, sometimes a year range with a from and to. But it's good to know that I can combine multiple arrays of filters like this. I will try experimenting with that.– zbroxAug 29, 2013 at 9:51
This code is not relevant to the source snippet you have provided. But for the sake of using OR
condition to filter collections you can use this.
// Get all event statuses.
$allowedStatus = array(
array("finset" => array('Running')),
array("finset" => array('Expired')),
array("finset" => array('Not Active')),
array("finset" => array('Test')),
);
// Filter by event status.
$collection->addAttributeToFilter("event_status", $allowedStatus); // This will filter objects which contains any one of the above statuses.
You can filter your result with the following set of example code
$collection =Mage::getModel('catalog/category')->load();
$collection->getProductCollection();
$collection->addAttributeToSelect('attribute1');
$collection->addAttributeToSelect('attribute2');
$collection->addAttributeToSelect('attribute3');
$collection->addAttributeToFilter(array(
array('attribute'=>'attribute1', 'finset'=>value1),
array('attribute'=>'attribute2', 'finset'=>value2),
array('attribute'=>'attribute3', 'finset'=>value3)
));