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 ?
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With