Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extend functionality of Mage_Eav_Model_Entity_Collection_Abstract::addAttributeToFilter
/**
* Add attribute filter to collection (extended)
*
* If $attribute is an array with following format, each condition will be
* separated by an OR, unless specified with a third 'and' property set to true:
*
* array(
* array('attribute'=>'firstname', 'like'=>'test%'),
* array('attribute'=>'lastname', 'like'=>'test%'),
* )
*
* or...
*
* array(
* array('attribute'=>'firstname', 'like'=>'test%'),
* array('attribute'=>'lastname', 'like'=>'test%', 'and' => true),
* )
*
* @see self::_getConditionSql for $condition
* @param Mage_Eav_Model_Entity_Attribute_Interface|integer|string|array $attribute
* @param null|string|array $condition
* @param string $joinType
* @param bool $and 'AND' conjunction by default; 'OR' if false
* @return Mage_Eav_Model_Entity_Collection_Abstract
*/
public function addAttributeToFilter($attribute, $condition = null, $joinType = 'inner', $and = true)
{
if ($attribute === null) {
$this->getSelect();
return $this;
}
if (is_numeric($attribute)) {
$attribute = $this->getEntity()->getAttribute($attribute)->getAttributeCode();
} else if ($attribute instanceof Mage_Eav_Model_Entity_Attribute_Interface) {
$attribute = $attribute->getAttributeCode();
}
if (is_array($attribute)) {
$sqlArr = array();
foreach ($attribute as $k => $condition) {
$conjunction = $k . ':' . (empty($condition['and']) ? 'OR' : 'AND');
$sqlArr[$conjunction] = $this->_getAttributeConditionSql($condition['attribute'], $condition, $joinType);
}
$conditionSql = '(';
foreach ($sqlArr as $conjunction => $arr) {
$conditionSql .= "{$arr}) " . explode(':', $conjunction)[1] . ' (';
}
$conditionSql = preg_replace('/(?: (?:OR|AND) \()$/', '', $conditionSql, 1) . ')';
} else if (is_string($attribute)) {
if ($condition === null) {
$condition = '';
}
$conditionSql = $this->_getAttributeConditionSql($attribute, $condition, $joinType);
}
$method = $and ? 'where' : 'orWhere';
if (!empty($conditionSql)) {
$this->getSelect()->{$method}($conditionSql, null, Varien_Db_Select::TYPE_CONDITION);
} else {
Mage::throwException('Invalid attribute identifier for filter ('.get_class($attribute).')');
}
return $this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.