How to Load Model Data By Custom Field in Magento 2
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?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()); } } } |
Also read: Alternative to Magento 2 Deprecated Load, Save and Delete Methods
If you have any doubts regarding the solution, feel free to mention them in the Comments section below. I’d be happy to help.
Also, do share the post with the Magento community via social media.
Thank you.
Chandresh Chauhan
He has been with Meetanshi for more than three years now as a certified Magento developer. A silent guy whom you can always find solving clients' issues, is an avid reader too.
Prev
How to Add Column to Customer Sales Order History Page in Magento 2
How to Add Google Analytics Code in Magento 2 [2024]
Next