addFieldToFilter

Updated . Posted . Visible to the public.

OR

$collection->addFieldToFilter('field_name', 
    [
        ['eq' => 'value1'],
        ['eq' => 'value2']
    ]
);
// same as
$collection->addFieldToFilter('field_name', ['value1', 'value2']);

Filter for X or Y

$collection->addFieldToFilter(
    ['k1' => 'mc_status', 'k2' => 'mc_fail'],
    ['k1' => ['in' => [21, 22]], 'k2' => ['null'=> true]]
);

The above retrieves:

SELECT `main_table`.* 
FROM `some_table` AS `main_table` 
WHERE ((mc_status IN(21, 22)) OR (mc_fail IS NULL))

NULL, NOT NULL

    ->addFieldToFilter('appl_id', ['notnull' => true])
    ->addFieldToFilter('some_id', ['null' => true])

IN an array

$ids = [20, 22, 25];
$collection = Mage::getResourceModel('customer/customer_collection')
    ->addAttributeToSelect($attributeCodes)
    ->addFieldToFilter('group_id', $groupId)
    ->addFieldToFilter('entity_id', ['in' => $ids]);

Time filtering

$ids = Mage::getResourceModel('sales/order_collection')
    ->addFieldToFilter('state', 'pending_payment')
    ->addFieldToFilter('created_at', ['to' => date('Y-m-d H:i:s', strtotime('-15 min'))])
    ->getAllIds();
->addFieldToFilter('entered_at', ['from' => $fromDate, 'to' => $toDate]);
->addFieldToFilter('created_at', ['from' => date('Y-m-d H:i:s', strtotime('-3 months'))]);
->addFieldToFilter('reg_end_at', ['from' => now()]); // now() format is 'Y-m-d H:i:s'

Find in Set, search in comma-delimited field:

$this->addFieldtoFilter('apply_to_groups', [
    ['finset'  => $groupId],
    ['null'    => true]
]);

regex

->addFieldToFilter('type', ['regexp'=> 'inn14.*|inn55.*'])

Ref Varien_Data_Collection_Db::_getConditionSql()

If $condition integer or string - exact value will be filtered ('eq' condition)
If $condition is array - one of the following structures is expected:


['from' => $fromValue, 'to' => $toValue] 
['eq' => $equalValue] 
['neq' => $notEqualValue] 
['like' => $likeValue] 
['nlike' => $notLikeValue]
['in' => [$inValues]] 
['nin' => [$notInValues]] // NOT IN
['notnull' => true] 
['null' => true] 
['gt' => $greaterValue] 
['lt' => $lessValue] 
['gteq' => $greaterOrEqualValue] 
['lteq' => $lessOrEqualValue] 
['finset' => $valueInSet] 
['regexp' => $regularExpression] 
['seq' => $stringValue] 
['sneq' => $stringValue] 
['is' => new Zend_Db_Expr('NULL')]

Complex Conditions 1

/**
 * Filter by ((condition1) OR (condition2))
 * 
 * @param int $studentId
 * @return $this
 */
public function filterLanguage($studentId)
{
    /**
     * condition1: include all courses without language requirement
     * @var Scx_Student_Model_Source_LanguageTest $source
     */
    $source = Mage::getSingleton('student/source_languageTest');
    $exams = $source->toOptionHash(false);
    $conditions = [];
    foreach ($exams as $exam => $label) {
        $conditions[] = $this->_translateCondition($exam, ['null' => true]);
    }
    $resultCondition = '(' . join(') ' . Zend_Db_Select::SQL_AND . ' (', $conditions) . ')';

    /**
     * condition2: add all courses in which the student's score meets the prerequisites
     * @var Scx_Student_Model_Resource_Language $resource
     */
    $resource = Mage::getResourceSingleton('student/language');
    if ($scores = $resource->getScores($studentId)) {
        $conditions = [];
        foreach ($scores as $exam => $score) {
            $conditions[] = $this->_translateCondition(
                $exam,
                ['lteq' => $score]
            );
        }
        $resultCondition = '(' . $resultCondition . ') '. Zend_Db_Select::SQL_OR
            . ' (' . join(') ' . Zend_Db_Select::SQL_OR . ' (', $conditions) . ')'
            ;
    }

    $this->_select->where($resultCondition);
    return $this;
}

SQL:

SELECT `main_table`.* 
FROM `scx_course_prerequisite` AS `main_table` 
WHERE (
    ((`ielts` IS NULL) AND (`toefl_pbt` IS NULL) AND (`toefl_ibt` IS NULL) AND (`muet` IS NULL) AND (`pte` IS NULL)) 
    OR (`toefl_ibt` >= '6.0')
)

Example 2

    /**
     * WHERE (
     *   (`prefix` = 'claim') AND (`object_id` = '1')
     *   OR
     *   (`prefix` = 'claim_item') AND (`parent_id` = '1')
     * )
     * @param string $parentPrefix
     * @param string $childPrefix
     * @param int $objectId
     * @return $this
     */
    public function filterParentChild($parentPrefix, $childPrefix, $objectId)
    {
        $and = Zend_Db_Select::SQL_AND;
        $conditions = [
            $this->_translateCondition('prefix', $parentPrefix),
            $this->_translateCondition('object_id', $objectId)
        ];
        $parentCond = implode(") $and (", $conditions);

        $conditions = [
            $this->_translateCondition('prefix', $childPrefix),
            $this->_translateCondition('parent_id', $objectId)
        ];
        $childCond = implode(") $and (", $conditions);

        $or = Zend_Db_Select::SQL_OR;
        $this->_select->where("($parentCond) $or ($childCond)");

        return $this;
    }
kiatng
Last edit
kiatng
Posted by kiatng to OpenMage (2015-08-19 01:52)