Mar 26, 2012

Magento: Hack - Nested addAttributeToFilter.

I already waste my one whole working day to look on this problem but still can file the solution. So I decide to modify the the magento core.

Here's the condition I want to do in addAttributeToFilter function.

(condition1) OR ((condition2) and (condition3) ..... )


To solve this Fucking problem I modify this class Mage_Eav_Model_Entity_Collection_Abstract.

public function addAttributeToFilter($attribute, $condition=null, $joinType='inner')
{
....Some Code here
if (is_array($attribute)) {
$sqlArr = array();
foreach ($attribute as $condition) {
$sqlArr[] = $this->_getAttributeConditionSql($condition['attribute'], $condition, $joinType);
}
$conditionSql = '('.join(') OR (', $sqlArr).')';
}else{
... your other code here.
}


Here my modify version.

public function addAttributeToFilter($attribute, $condition=null, $joinType='inner')
{
....Some Code here
if (is_array($attribute)) {
$sqlArr = array();
$myAND = array();
$andSqlArr = array();
/*
* @ win mode to support (x=a) or (y=1 and z=0)
* array(
* array(condition)
* 'and' =>
* array(
* array(condition)
* array(condition)
* ),
* )
*
* Output expected
* cond1 OR (cond2 and cond3)
*/
foreach ($attribute as $key => $condition) {
if ($key === "and"){
$myAND = $condition;
continue;
}
$sqlArr[] = $this->_getAttributeConditionSql($condition['attribute'], $condition, $joinType);
}
foreach ($myAND as $key => $andCond ){
$andSqlArr[] = $this->_getAttributeConditionSql(
$andCond['attribute'],
$andCond,
$joinType);
}
$conditionSql = '('.join(') AND (', $andSqlArr).')';
if ($andSqlArr){
$sqlArr[] = $conditionSql;
}

$conditionSql = '('.join(') OR (', $sqlArr).')';
}
... your other code here.
}


In your product collection.

$collection->addFieldToFilter(
array(
array("attribute"=>"your_attribute1", "in"=>array(1,2,3,)),
"and" => array(
array("attribute"=>"your_attribute2", "eq"=>1,),
array("attribute"=>"your_attribute3", "eq"=>1,),
),
)
);


Happy Coding. :)

No comments: