Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if collection contains data

Tags:

magento

It may be a simple question, but I can't find the answer. How can I know if my Collection has no data ?

I do $datas = Mage::getModel('zzz/zzz')->getCollection() if I do a $datas->getData() it returns an empty array, but how do I know if my collection has no data without doing foreach or getData ?

like image 579
Shadowbob Avatar asked Mar 11 '13 15:03

Shadowbob


1 Answers

You should avoid using count or your Collections. Here's why:

the Mage_Core_Model_Resource_Db_Collection_Abstract (Collection Model that is inherited by almost all Magento Collections) does not have count() defined, so using count on your Collection you'll most likely end up with Varien_Data_Collection::count() which is very bad option, since it does a collection load() and then counts the loaded objects:

/**
 * Retireve count of collection loaded items
 *
 * @return int
 */
public function count()
{
    $this->load();
    return count($this->_items);
}

Having a large collection (especially EAV collection) will make result in loading ALL of your Collection data - this can take a lot of time.

Instead you should use Varien_Data_Collection_Db::getSize() method, which will run the SQL query to get count only, much more optimized compared to retrieving all kind of data for Collection load:

/**
 * Get collection size
 *
 * @return int
 */
public function getSize()
{
    if (is_null($this->_totalRecords)) {
        $sql = $this->getSelectCountSql();
        $this->_totalRecords = $this->getConnection()->fetchOne($sql, $this->_bindParams);
    }
    return intval($this->_totalRecords);
}

In addition to that, after load collection can not be modified in any way. For example you won't be able to apply additional filters of change sort order at any point after using count().

So correct answer should be:

$collection = Mage::getModel('zzz/zzz')->getCollection();
var_dump($collection->getSize());
like image 63
Slayer Birden Avatar answered Sep 27 '22 17:09

Slayer Birden