Magento 2βs Collection objects (like product, order, customer collections, etc.).
π’ Filtering & Adding Conditions
- addFilter($field, $value, $type=’and’)
Adds a basic filter on a field. Mostly used internally. You generally use addFieldToFilter instead.
Example:
$collection->addFilter(‘status’, 1);
- addFieldToFilter($field, $condition)
Most commonly used to filter data from collections.
Example:
$collection->addFieldToFilter(‘status’, [‘eq’ => 1]);
$collection->addFieldToFilter(‘name’, [‘like’ => ‘%mobile%’]);
- getFilter($field)
Gets the filter value you previously added (used internally in rare custom cases).
π’ Pagination & Page Information
- isLoaded()
Returns true if the collection has already fetched data from the database.
Usage:
if (!$collection->isLoaded()) {
$collection->load();
}
- getCurPage($displacement=0)
Gets the current page number of the collection.
- getLastPageNumber()
Gives the last page number (total pages based on item count and page size).
- getPageSize()
Returns how many items will appear per page.
- getSize()
Returns total number of records available in the collection (without pagination).
π’ Working with Items
- getFirstItem()
Returns the first item of the collection.
- getLastItem()
Returns the last item of the collection.
- getItems()
Returns all items as an array (key => DataObject).
- getColumnValues($colName)
Returns all values of a specific column.
Example:
$collection->getColumnValues(‘sku’); // [‘SKU1’, ‘SKU2’, …]
- getItemsByColumnValue($column, $value)
Gets all items that match a column value.
Example:
$collection->getItemsByColumnValue(‘status’, 1);
- getItemByColumnValue($column, $value)
Gets the first item that matches a column value.
- addItem(\Magento\Framework\DataObject $item)
Manually adds a new item to the collection (rarely used unless working with custom data).
π’ Modifying Collection Items
- getAllIds()
Returns an array of all entity IDs.
Example:
$collection->getAllIds(); // [1,2,3…]
- removeItemByKey($key)
Removes an item by its internal key (use carefully).
- removeAllItems()
Clears the entire collection.
- clear()
Same as removeAllItems(), resets the collection object.
π’ Apply Actions to All Items
- walk($callback, array $args=[])
Applies a method to all items.
Example:
$collection->walk(‘delete’);
- each($objMethod, $args=[])
Similar to walk(), applies a method to each item and returns the result.
π’ Set Data to All Items
- setDataToAll($key, $value=null)
Sets a key-value pair to all items in the collection.
Example:
$collection->setDataToAll(‘is_selected’, true);
π’ Pagination Settings
- setCurPage($page)
Set which page to load.
- setPageSize($size)
How many records to show per page.
π’ Sorting
- setOrder($field, $direction=self::SORT_ORDER_DESC)
Sets the sorting order.
Example:
$collection->setOrder(‘created_at’, ‘DESC’);
π’ Advanced & Internal Usage
- setItemObjectClass($className)
Changes the type of items stored in the collection. Used internally or in custom data objects.
- getNewEmptyItem()
Returns a blank DataObject matching the collection item type.
- distinct($flag)
If set to true, adds DISTINCT to the SQL query (removes duplicates).
- loadData($printQuery=false, $logQuery=false)
Loads the collection data explicitly. printQuery/logQuery for debugging SQL.
- load($printQuery=false, $logQuery=false)
Same as loadData(). Used to trigger data fetch.
- loadWithFilter($printQuery=false, $logQuery=false)
Loads the data applying current filters. Rarely used directly.
π’ Conversion Methods
- toXml()
Returns XML representation of collection (mostly legacy, rarely used).
- toArray($arrRequiredFields=[])
Converts the collection to an array.
- toOptionArray()
Commonly used for dropdowns (label => value format).
Example use: in system.xml select field.
- toOptionHash()
Returns array like [‘id1’ => ‘label1’, …] – used in admin dropdowns too.
π’ Searching
- getItemById($idValue)
Returns item with that specific ID.
- getIterator()
Returns iterable object (foreach friendly).
- count()
Returns number of loaded items (note: not total in DB, thatβs getSize()).
π’ Flags (Internal Tracking)
- getFlag($flag)
- setFlag($flag, $value=null)
- hasFlag($flag)
Used to track internal collection states or custom info.
π’ Serialization Methods
- __sleep()
Used during object serialization (internal).
- __wakeup()
Used during object unserialization (internal).
π Summary Table
Purpose | Functions |
---|---|
Filtering | addFilter, addFieldToFilter |
Pagination | setCurPage, setPageSize, getCurPage, getLastPageNumber |
Sorting | setOrder |
Data Access | getItems, getFirstItem, getLastItem, getItemById |
Utility | getSize, getAllIds, getColumnValues |
Modifying Items | setDataToAll, removeItemByKey, clear |
Conversion | toArray, toOptionArray, toOptionHash |