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?
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.
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)
...
Try as:
$collection = Mage::getResourceModel('mymodule/mymodel_collection')->addFieldFilter('myattribute', $value);
$collection->count();
//or
$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