Magento 2 Collection Cheat Sheet

Magento 2 Collection is powerful. You can create custom entities and extend the default Magento capabilities. I am using this cheat sheet to record commonly use code sample. So, every time I need it I know where to look for. Please note that I haven’t detailed the solutions here as this is only a quick reference.

Get the First and last item from a Magento 2 Collection

In some cases, you will have to get the first or last element of a collection. This can be a product, category or your custom collection. it is always good practice to check the size of the collection before you apply getFirstItem() or getLastItem().

$data = $collection->getFirstItem();

Get Order Items from Order Item Collection

Programitically get Magento Sales Order Items without going through sales oders.

\Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory $orderItemCollection,

$orderItems = $this->_orderItemCollection->create();
$orderItems->addAttributeToFilter('field_name', $fieldValue);


More Posts

What is Visual Positioning System?

A visual positioning system (VPS) is a technology that uses visual cues from the environment to determine the position and orientation of a device or

Setup Shopify Store

To set up a Shopify store, follow these steps: Go to https://www.shopify.com/ and click on the “Start free trial” button. Enter your email address and

Let's Talk