Cheat Sheet: Magento Collection Snippets

August 18th, 2016

Warning: This post is 8 years old. Some of this information may be out of date.

A cheat sheet containing useful Magento Collection snippets.

Count number of items in a collection

    $collection = Mage::getModel('some/model')->getCollection()
        ->addFieldToFilter('customer_id', ['eq' => $userId])
        ->addFieldToFilter('product_id', ['eq' => $productId]);
    
    // get count
    echo $collection->count();

Alternatively, you can make Magento rewrite the SQL to use a COUNT() function:

    $collection = Mage::getModel('some/model')->getCollection()
        ->addFieldToFilter('customer_id', ['eq' => $userId])
        ->addFieldToFilter('product_id', ['eq' => $productId])
        ->setSize();

Set GROUP BY by clause

    $collection = Mage::getModel('some/model')->getCollection()
        ->addFieldToFilter('customer_id', ['eq' => $userId])
        ->addFieldToFilter('product_id', ['eq' => $productId]);
    
    // this is where we add the group by  
    $collection->getSelect()->group('main_table.sku');
    
    $collection->setOrder('updated_at', 'DESC');

Get First Item from a collection

    $item = $collection->getFirstItem();