Magento 2’s Collection objects.

Magento 2’s Collection objects (like product, order, customer collections, etc.).

🟒 Filtering & Adding Conditions

  1. 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);

  1. addFieldToFilter($field, $condition)

Most commonly used to filter data from collections.

Example:
$collection->addFieldToFilter(‘status’, [‘eq’ => 1]);
$collection->addFieldToFilter(‘name’, [‘like’ => ‘%mobile%’]);

  1. getFilter($field)

Gets the filter value you previously added (used internally in rare custom cases).

🟒 Pagination & Page Information

  1. isLoaded()

Returns true if the collection has already fetched data from the database.

Usage:
if (!$collection->isLoaded()) {
$collection->load();
}

  1. getCurPage($displacement=0)

Gets the current page number of the collection.

  1. getLastPageNumber()

Gives the last page number (total pages based on item count and page size).

  1. getPageSize()

Returns how many items will appear per page.

  1. getSize()

Returns total number of records available in the collection (without pagination).

🟒 Working with Items

  1. getFirstItem()

Returns the first item of the collection.

  1. getLastItem()

Returns the last item of the collection.

  1. getItems()

Returns all items as an array (key => DataObject).

  1. getColumnValues($colName)

Returns all values of a specific column.

Example:
$collection->getColumnValues(‘sku’); // [‘SKU1’, ‘SKU2’, …]

  1. getItemsByColumnValue($column, $value)

Gets all items that match a column value.

Example:
$collection->getItemsByColumnValue(‘status’, 1);

  1. getItemByColumnValue($column, $value)

Gets the first item that matches a column value.

  1. addItem(\Magento\Framework\DataObject $item)

Manually adds a new item to the collection (rarely used unless working with custom data).

🟒 Modifying Collection Items

  1. getAllIds()

Returns an array of all entity IDs.

Example:
$collection->getAllIds(); // [1,2,3…]

  1. removeItemByKey($key)

Removes an item by its internal key (use carefully).

  1. removeAllItems()

Clears the entire collection.

  1. clear()

Same as removeAllItems(), resets the collection object.

🟒 Apply Actions to All Items

  1. walk($callback, array $args=[])

Applies a method to all items.

Example:
$collection->walk(‘delete’);

  1. each($objMethod, $args=[])

Similar to walk(), applies a method to each item and returns the result.

🟒 Set Data to All Items

  1. setDataToAll($key, $value=null)

Sets a key-value pair to all items in the collection.

Example:
$collection->setDataToAll(‘is_selected’, true);

🟒 Pagination Settings

  1. setCurPage($page)

Set which page to load.

  1. setPageSize($size)

How many records to show per page.

🟒 Sorting

  1. setOrder($field, $direction=self::SORT_ORDER_DESC)

Sets the sorting order.

Example:
$collection->setOrder(‘created_at’, ‘DESC’);

🟒 Advanced & Internal Usage

  1. setItemObjectClass($className)

Changes the type of items stored in the collection. Used internally or in custom data objects.

  1. getNewEmptyItem()

Returns a blank DataObject matching the collection item type.

  1. distinct($flag)

If set to true, adds DISTINCT to the SQL query (removes duplicates).

  1. loadData($printQuery=false, $logQuery=false)

Loads the collection data explicitly. printQuery/logQuery for debugging SQL.

  1. load($printQuery=false, $logQuery=false)

Same as loadData(). Used to trigger data fetch.

  1. loadWithFilter($printQuery=false, $logQuery=false)

Loads the data applying current filters. Rarely used directly.

🟒 Conversion Methods

  1. toXml()

Returns XML representation of collection (mostly legacy, rarely used).

  1. toArray($arrRequiredFields=[])

Converts the collection to an array.

  1. toOptionArray()

Commonly used for dropdowns (label => value format).

Example use: in system.xml select field.

  1. toOptionHash()

Returns array like [‘id1’ => ‘label1’, …] – used in admin dropdowns too.

🟒 Searching

  1. getItemById($idValue)

Returns item with that specific ID.

  1. getIterator()

Returns iterable object (foreach friendly).

  1. count()

Returns number of loaded items (note: not total in DB, that’s getSize()).

🟒 Flags (Internal Tracking)

  1. getFlag($flag)
  2. setFlag($flag, $value=null)
  3. hasFlag($flag)

Used to track internal collection states or custom info.

🟒 Serialization Methods

  1. __sleep()

Used during object serialization (internal).

  1. __wakeup()

Used during object unserialization (internal).

πŸ“Œ Summary Table

PurposeFunctions
FilteringaddFilter, addFieldToFilter
PaginationsetCurPage, setPageSize, getCurPage, getLastPageNumber
SortingsetOrder
Data AccessgetItems, getFirstItem, getLastItem, getItemById
UtilitygetSize, getAllIds, getColumnValues
Modifying ItemssetDataToAll, removeItemByKey, clear
ConversiontoArray, toOptionArray, toOptionHash

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top