Magento Snippet: Use a Group By clause on a collection model


Posted by Andrew McCombe on Wed Aug 17, 2016

Here’s a Magento snippet showing how to use a Group By clause on a Magento collection model.

<?php

// ....

$collection = Mage::getModel('sales/order_item')->getCollection();
$collection
    ->addAttributeToFilter('updated_at', array('gt' => $this->reportStartDate)) 
    ->addAttributeToFilter('updated_at', array('lt' => $this->reportEndDate));

// this is where we add the group by  
$collection->getSelect()->group('main_table.sku');

$collection->setOrder('updated_at', 'DESC');