Cheat Sheet: Magento Collection Snippets

August 18, 2016

Image for Cheat Sheet: Magento Collection Snippets from unsplash.com

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();