Filter EAV collection

Updated . Posted . Visible to the public.

condA AND (cond1 OR cond2 OR cond3)

$cincId = $session->getCustomerId();
$attributes = array( 
    array('attribute'=>'mc_by', 'eq'=>$clinicId), 
    array('attribute'=>'mc_lb_by', 'eq'=>$clinicId),
    array('attribute'=>'mc_xy_by','eq'=>$clinicId), 
);               
$students = Mage::getResourceModel('moe/stut_collection')
    ->addAttributeToSelect(array('fullname', 'travel_doc_no', 'mc_status'))
    ->addAttributeToFilter($attributes, null, 'left')
    ->setOrder('created_at', 'desc')
;

Short Array:

    /**
     * @param string $query
     * @param bool $exactMatch
     * @return $this
     */
    public function filterTdnOrNic($query, $exactMatch = false)
    {
        if ($exactMatch) {
            $op = 'eq';
        } else {
            $op = 'like';
            $query .= '%';
        }
        return $this->addAttributeToFilter([
            ['attribute' => 'tdn', $op =>  $query],
            ['attribute' => 'nic', $op =>  $query]
        ]);
    }

cond1 OR (condA AND condB)

    public function filterClientOf($user)
    {
        $cond1 = $this->_getAttributeConditionSql('client_of_id', $user->getId());
        $sqlArr[] = $this->_getAttributeConditionSql('shared_level', 'group');
        $sqlArr[] = $this->_getAttributeConditionSql('medical_group_id', $user->getCompanyId());
        $cond2 = '(' . implode(') AND (', $sqlArr) . ')';

        $conditionSql = '(' . $cond1 . ') OR (' . $cond2 . ')';
        $this->getSelect()->where($conditionSql, null, Varien_Db_Select::TYPE_CONDITION);

        return $this;
    }

Resulting SQL:

SELECT `e`.`entity_id`, `e`.`email`, `e`.`is_active`, `at_client_of_id`.`value` AS `client_of_id` 
FROM `customer_entity` AS `e`
 INNER JOIN `customer_group` AS `g` ON e.group_id = g.customer_group_id
 INNER JOIN `customer_entity_int` AS `at_client_of_id` 
  ON (`at_client_of_id`.`entity_id` = `e`.`entity_id`) 
    AND (`at_client_of_id`.`attribute_id` = '234')
 INNER JOIN `customer_entity_varchar` AS `at_shared_level` 
  ON (`at_shared_level`.`entity_id` = `e`.`entity_id`) 
    AND (`at_shared_level`.`attribute_id` = '235')
 INNER JOIN `customer_entity_int` AS `at_medical_group_id` 
  ON (`at_medical_group_id`.`entity_id` = `e`.`entity_id`) 
   AND (`at_medical_group_id`.`attribute_id` = '240') 
WHERE (`e`.`entity_type_id` = '1') 
  AND (g.customer_group_code = 'Corporate Client') 
  AND (
   (at_client_of_id.value = '1') 
   OR (
     (at_shared_level.value = 'group') AND (at_medical_group_id.value = '938')
   ))

Sort Order in EAV Collection

    /**
     * Filter by group name(s).
     *
     * @param string|string[]
     * @return $this
     * @throws Mage_Core_Exception
     * @throws Mage_Core_Model_Store_Exception
     * @throws Zend_Db_Select_Exception
     */
    public function filterGroup($groupCode = 'Clinic')
    {
        $this->getSelect()->join(
            ['g' => $this->getTable('customer/customer_group')],
            'e.group_id = g.customer_group_id',
            []
        );

        if (is_array($groupCode)) {
            $this->getSelect()->where('g.customer_group_code IN (?)', $groupCode);
        } else {
            $this->getSelect()->where('g.customer_group_code = ?',  $groupCode);
        }

        return $this;
    }

         /** @var Mage_Customer_Model_Resource_Customer_Collection $collection */
         $collection
            ->filterGroup()
            ->addNameToSelect()
            ->setOrder(['prefix', 'firstname', 'middlename', 'lastname', 'suffix']);

Join a Backend Table

    /**
     * Get attribute params.
     *
     * @return array
     */
    protected function _getAttributeParams()
    {
        $attribute = Mage::getModel('extendedcustomer/attribute')->loadByAttributeCode('wallet_id');
        return [$attribute->getBackendTable(), $attribute->getEntityTypeId(), $attribute->getAttributeId()];
    }

    /**
     * Create wallets.
     *
     * @param Mage_Cron_Model_Schedule|null $schedule
     * @return array|void
     */
    public function wallet($schedule = null)
    {
        if (!Mage::getStoreConfigFlag('jim_api/smart_app/enabled')) {
            return;
        }

        [$backendTable, $entityTypeId, $attributeId] = $this->_getAttributeParams();

        $installer = Mage::getResourceModel('core/setup', 'emgs_setup');
        $db = $installer->getConnection();
        $table  = $installer->getTable('sales/order_grid');
        $select = $db->select()
            ->from(['o' => $table], ['applicant_id'])
            ->joinLeft(
                ['a' => $backendTable],
                "o.applicant_id = a.entity_id AND a.attribute_id = $attributeId",
                []
            )
            ->where('a.value IS NULL')
            ->where('o.type LIKE ?', 'im14%')
            ->where('o.invoice_created_at >= ?', date('Y-m-d', strtotime('-1 year')))
            ->group('applicant_id')
            //->limit(2)
        ;

        //return $select->__toString();
        $ids = $db->fetchCol($select);
        //...

IMPORTANT: Note the JOIN ... ON condition: "o.applicant_id = a.entity_id AND a.attribute_id = $attributeId", has attribute_id for it to set null value on missing value.

kiatng
Last edit
kiatng
Posted by kiatng to OpenMage (2014-03-07 01:45)