Question

I want to get count after the collection filter by attributes.Actually i want filter order collections by non canceled ,non fraud' and use getSize() function to get count but it is given count result as when any filters not applied.

Please suggest what i do in this caseto get proper result of count.I have order 630 and when i use count() function on collection filter it give proper result.

$orderCollection = Mage::getModel('sales/order')->getCollection();

echo $orderCollection->getSize().'---'; // Result 630
                //$orderCollection->addFieldToFilter('customer_id',$customer->getId());
$orderCollection->addFieldToFilter('state', array('nin' => array('pending_payment', 'canceled', 'fraud', 'payment_review', 'pending', 'pending_paypal', 'closed')));

echo $orderCollection->size(); // result give 630


echo $orderCollection->count(); // given 305  proper result.

I guess that may load() function is working for getCount() that why it is ok. I have check the link Difference between getSize() and count() on collection

My question, is my concept is right?

Was it helpful?

Solution

Your problem is that you call getSize() twice and you modify the collection between the calls.
Take a look at how getSize() works.

public function getSize()
{
    if (is_null($this->_totalRecords)) {
        $sql = $this->getSelectCountSql();
        $this->_totalRecords = $this->getConnection()->fetchOne($sql, $this->_bindParams);
    }
    return intval($this->_totalRecords);
} 

So the first time you call getSize() you get the correct result 630.
Then you add an other filter to the collection and call getSize() again.
But the first time you call getSize() the value is remembered in $this->_totalRecords.
the second time you call it, the query is not executed again because $this->_totalRecords is not null and the method just returns the value you have already set, 630 in your case.

You can remove the first getSize()call if you don't need it.
If you need it you can do this:

//clone the collection object
$clone = clone $orderCollection;
//get the total size from the clone
echo $clone->getSize();
//add the filter to the original object
$orderCollection->addFieldToFilter('state', array('nin' => array('pending_payment', 'canceled', 'fraud', 'payment_review', 'pending', 'pending_paypal', 'closed')));
//get the size of the filtered collection
echo $orderCollection->size(); 
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top