Collection Manipulation (Filtering, Limiting, etc)

Updated . Posted . Visible to the public.

A list of collection methods, similar to this Show archive.org snapshot

Where

OR:

You have to first specify an array of attributes in the filter, then a two dimensional array, with each second dimension have the filters for attribute n, as below:

$this->addFieldToFilter(
    array('email', 'customer_id'),
    array(
        array('eq' => $customer->getEmail()), // filters for e-mail
        array('eq' => $customer->getId()), // filters for customer_id
    )
);

The above results in this SQL:

SELECT `main_table`.* FROM `wherever` AS `main_table` WHERE ((email = 'noone@nowhere.com') OR (customer_id = '10'))

Order

Don't get fooled by the lack of an order statement on the SQL output, even when one is added, as below:

$collection->setOrder('name', 'ASC');
echo (string) $collection->getSelect();

The reason that the ORDER BY statement is not in the select is that orders get added to the select upon load(), so this would work:

$collection->setOrder('name', 'ASC');
$collection->load();
echo (string) $collection->getSelect();

Limit

The same applies to limit as does to order in respect of statement not being present until after load() is called.

$collection->getSelect()->limit(1);
Mike Whitby
Last edit
Mike Whitby
Posted by Mike Whitby to Magento (2012-03-20 13:15)