cancel
Showing results for 
Search instead for 
Did you mean: 

Nested AND statement within an OR statement

Nested AND statement within an OR statement

I currently have this model in Magento:

    	$model = Mage::getModel('catalog/product')->getCollection();
        $model->addAttributeToFilter(
    		array(
    	        array( // AND
    	            array('attribute'=> 'someattribute','like' => 'value'),
    	            array('attribute'=> 'otherattribute','like' => 'value'),
    	        ),
    	        array('attribute'=> 'otherattribute','like' => '5'),
    	    )
        );


Accoarding to tutorials, this should return this SQL statement (the desired result):

SELECT ... WHERE ((someattribute LIKE 'value' AND otherattribute LIKE 'value') OR (anotherattribute LIKE '5'));

But instead, Magento returns this:

 

Notice: Undefined index: attribute in .../Mage/Eav/Model/Entity/Collection/Abstract.php on line 314

When I remove the first array, it does return an SQL statement, but instead of doing the SQL query as intended, it returns this:

SELECT ... WHERE ((someAttribute LIKE 'value') OR (otherattribute LIKE 'value'));

It seems to compleatly drop the third value (which is logical if the first statement would be correct).

Does anyone know what I do wrong here?

1 REPLY

Re: Nested AND statement within an OR statement

include_once 'abstract.php';

class A extends Mage_Shell_Abstract {
	
	public function run() {
		
		$col = Mage::getModel('catalog/product')->getCollection();
		$col->addAttributeToFilter(array(
					array(
						'attribute' => 'sku',
						'like' => '%ch%'),
					array(
						'attribute' => 'status',
						'eq' => '1')
				));

			$col->addAttributeToFilter('name', array('like' => 'dsw'));
			return $col->getSelect()->__toString();
	}
}

$test = new A();
echo $test->run();

And the output:

 

SELECT `e`.*, `at_status`.`value` AS `status`, `at_name`.`value` AS `name` FROM `sl_catalog_product_entity` AS `e` INNER JOIN `sl_catalog_product_entity_int` AS `at_status` ON (`at_status`.`entity_id` = `e`.`entity_id`) AND (`at_status`.`attribute_id` = '96') AND (`at_status`.`store_id` = 0) INNER JOIN `sl_catalog_product_entity_varchar` AS `at_name` ON (`at_name`.`entity_id` = `e`.`entity_id`) AND (`at_name`.`attribute_id` = '71') AND (`at_name`.`store_id` = 0) WHERE ((`e`.`sku` LIKE '%ch%') OR (at_status.value = '1')) AND (at_name.value LIKE 'dsw')

 

Unfortunatelly there is no built-in method to mix conditions in order (X and Y) or Z