Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento - Most efficient method of getting a collection count

Tags:

magento

I have a helper method in Magento which requires me to get the count of several unrelated collections. Further to this, i need this information for each product in a category i.e. for each product in the product list view. So i will potentially be creating lots of collections repeatedly during the product list rendering.

What is the most efficient method of getting the count of a collection, that is, i do not need any data from the models, simply how many models there are.

Is it simply:

Mage::getResourceModel('mymodule/mymodel_collection')->addFilter('myattribute', $value)->count()

Or is there a more efficient way to do this?

like image 344
John Wilson Avatar asked Jul 10 '12 15:07

John Wilson


People also ask

What is collection in Magento?

Collections in Magento are extremely useful, they allow you to retrieve objects such as products, categories, customers, etc. Retrieving these objects in a collection is a simple case of instantiating an instance of the object entity's factory class and using the model's 'getCollection' method, as follows.


2 Answers

For counting items in a collection, use the getSize() method:

$collection->getSize();

Never use the php count() function or the count() method of the collection like this:

count($collection)
$collection->count()

When you use the count() function/method, Magento loads all the items of the collection from the database. On large collections you will have an huge memory usage and possibly issues like Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)...

like image 124
FLOZz Avatar answered Oct 04 '22 03:10

FLOZz


Try as:

$collection = Mage::getResourceModel('mymodule/mymodel_collection')->addFieldFilter('myattribute', $value);
$collection->count();
//or
$collection->getSize();
like image 30
MagePsycho Avatar answered Oct 04 '22 04:10

MagePsycho