How to Use Where Condition in Customer Collection – Magento 1.9

collection-filteringcollection;customermagento-1.9

I have filed 'read' in alireza_checkingout_checkingout table I want to add condition if read =0 in query below, I alreadt tried ->addFieldToFilter('read', array('eq' => 0)) but the system return an error "fatal error: Call to a member function getBackend() on boolean in /var/www/html/megadump/app/code/core/Mage/Eav/Model/Entity/Abstract.php on line 816"

$collection = Mage::getResourceModel('customer/customer_collection')

 ->addNameToSelect()
 ->addAttributeToSelect('email')
 ->addAttributeToSelect('created_at')
 ->addAttributeToSelect('group_id')
 ->joinTable('alireza_checkingout_checkingout','alireza_customer_id=entity_id',array('alireza_customer_id','read'),null,'left')
 ->joinAttribute('billing_postcode', 'customer_address/postcode', 'default_billing', null, 'left')
 ->joinAttribute('billing_city', 'customer_address/city', 'default_billing', null, 'left')
 ->joinAttribute('billing_telephone', 'customer_address/telephone', 'default_billing', null, 'left')
 ->joinAttribute('billing_region', 'customer_address/region', 'default_billing', null, 'left')
 ->joinAttribute('billing_country_id', 'customer_address/country_id', 'default_billing', null, 'left');
 $collection->getSelect()->columns('count(alireza_customer_id) as cc')->group('entity_id');
 $this->setCollection($collection);

 return Mage_Adminhtml_Block_Widget_Grid::_prepareCollection();

Best Answer

In EAV models, like the customer, addFieldToFilter is an alias for addAttributeToFilter and only works if the parameter ("read" in your case) is a real EAV attribute of the customer and not a field in the customer_entity table, or any other table.

The error message hints that there is no attribute ($attribute->getBackend() fails because there was no attribute found).

But if read actually is a field in the entity table, you can tell the collection so, using addStaticField():

$collection->addStaticField('read')->addFieldToFilter('read', array('eq' => 0));

Update: I see that the field actually is from a joined table. You need to use joinAttribute or joinField to allow using the field for filters.

I assume, alireza_checkingout_checkingout is a regular table, not an EAV entity:

Replace

->joinTable('alireza_checkingout_checkingout','alireza_customer_id=entity_id',array('alireza_customer_id','read'),null,'left')

with

->joinField('read', 'alireza_checkingout_checkingout', 'read', 'alireza_customer_id=entity_id')

You can even add the filter immediately, as joinField has a $cond parameter:

->joinField('read', 'alireza_checkingout_checkingout', 'read', 'alireza_customer_id=entity_id', '{table}.read=0')

The condition will be added to the ON clause of the join, which is by default an INNER JOIN, so the result is the same as using addFieldToFilter.

Related Topic