In most instances, Magento 2 developers use Model to load records. Generally, models in Magento 2 are loaded by the field with the primary key.
At the time of client’s requirements where they want to load model data using a non-primary column field, you can use the programmatic method below to load model data by custom field in Magento2.
Generally, we use addFieldToFilter on collection and getFirstItem or loop over the collection. Though, we can use the model to load data based on any custom column.
Let us understand with an example. If you are working with a custom model and you don’t have an ID or any other data of the customer, but you have to load the model data by other custom fields like email_id or quote_id. Here’s the solution to load model data by custom field in Magento2!
Programmatic Method to Load Model Data by Custom Field
<?php namespace [Vendor]\[Module]\Helper; use Magento\Framework\App\Helper\Context; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Sales\Model\OrderFactory; use [Vendor]\[Module]\Model\CustomFactory; class Data extends AbstractHelper { protected $orderCollectionFactory; protected $customFactory; public function __construct( Context $context, OrderFactory $orderCollectionFactory, CustomFactory $customFactory ) { $this->orderCollectionFactory = $orderCollectionFactory; $this->customFactory = $customFactory; parent::__construct($context); } public function getCustomData() { try { $quoteID = 11; // you can change quoteID $collection = $this->orderCollectionFactory->create()->load($quoteID, 'quote_id'); // custom model example $custom_id = 5; $customCollection = $this->customFactory->create()->load($custom_id, 'custom_id'); } catch (\Exception $e) { $this->_logger->info($e->getMessage()); } } }
That’s all!
Also read: Alternative to Magento 2 Deprecated Load, Save and Delete Methods
Also, do share the post with the Magento community via social media.
Thank you.