Magento 2 offers to fetch the data from the default database table.
However, to get data from custom database table in Magento 2, one will need to implement the solution below.
You can use this code to get data for a custom module you developed or any custom feature for which you’ll need data from a custom database table.
Also, if you want to display any custom data on the frontend, for example, show customers’ mobile number on the cart page or My Account, you’ll have to fetch the data for implementing the same. If you are a developer.
Method to get data from custom database table in Magento 2:
Create Data.php in app/code/[Vendor]/[Module]/Helper
<?php namespace [Vendor]\[Module]\Helper; use [Vendor]\[Module]\Model\CustomModelFactory; class Data extends \Magento\Framework\App\Helper\AbstractHelper { protected $customModelFactory; public function __construct( Context $context, CustomModelFactory $customModelFactory, array $data = array() ) { $this->customModelFactory = $customModelFactory; parent::__construct($context, $data); } public function getCollection() { return $this->customModelFactory->create()->getCollection(); } }
Now, you can use a helper function to get the custom table model collection as per your requirement.
That’s it.
Do share the solution with Magento community via social media.
Thank you.
Related Post