magento

Collections

Get Model Collections

// get existing collections
$orders = Mage::getModel('sales/order')->getCollection();
$products = Mage::getModel('catalog/product')->getCollection();
$customers = Mage::getModel('customer/customer')->getCollection();

Get Additional Object Attributes

// $orders is collection
$orders->addAttributeToSelect('status'); // get status attribute
$orders->addAttributeToSelect('*'); // get all attributes

Filtering

// filter by creation date
$date = new Zend_Date();
$toDate = $date->get(Zend_Date::W3C); // today
$fromDate = $date->sub('1', Zend_Date::MONTH)->get(Zend_Date::W3C); // one month ago

$orders->addAttributeToFilter('created_at', array('from' => $fromDate, 'to' => $toDate));

// more filtering, type AND
$orders->addAttributeToFilter('status', 'pending');
$orders->addAttributeToFilter('state', array('nlike' => 'new'));

// more filtering, type OR
$processing = array('eq' => 'processing');
$complete = array('like' => 'complete');
$orders->addAttributeToFilter('status', array($processing, $complete));

Sorting

// sort by creation date
$orders->setOrder('created_at', 'asc');
$orders->setOrder('created_at', 'desc'); 
$orders->setOrder('created_at'); // default direction is 'desc'

Access

// iterating over items in collection
foreach ($orders as $singleOrder) {
    // do something with individual objects
    var_dump($singleOrder->getData());
}

// get first/last item in collection
$first = $orders->getFirstItem();
$last = $orders->getLastItem();

Get Collection Object

    // get product collection object
    $productCollection = Mage::getResourceModel('catalog/product_collection');
    // get customer collection object
    $customerCollection = Mage::getResourceModel('customer/customer_collection');
    // get order collection object
    $orderCollection = Mage::getResourceModel('sales/order_collection');

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow