WM SANJAYA

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().

if($collection->getSize()){
$data = $collection->getFirstItem();
$data->getId();
$data->getName();
}

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);
$orderItems->load();

Share:

More Posts

Setup Shopify Store

Create a new Shopify Account (14 day Trail) Add Billing and Store Details Add domain name Make sure you register your domain through Godaddy/External domain

Let's Talk