Hello Guys, We can create a custom resource model in Magento2 using following custom module extension and can use it for querying the database with our custom SQL statements and collections. Let's create a resource model with following steps defined. Step 1: We need to create an module.xml in app/code/Magemeta/Override/etc/module.xml to register our custom module.<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd"> <module name="Magemeta_Override" setup_version="1.0.0"/> </config>
Step 2: We need to create an Test.php in app/code/Magemeta/Override/Model/ResourceModel/Test.php to register our custom resource model class. In this class, we have declared _construct() method where we will initialise our custom resource model with it's associated table with primary key which will act as a main table for this resource model.<?php namespace Magemeta\Override\Model\ResourceModel; use Magento\Framework\Model\ResourceModel\Db\AbstractDb; /** * Class Test * @package Magemeta\Override\Model\ResourceModel */ class Test extends AbstractDb { /** * Test constructor. * @param \Magento\Framework\Model\ResourceModel\Db\Context $context */ public function __construct( \Magento\Framework\Model\ResourceModel\Db\Context $context ) { parent::__construct($context); } /** * Initialize ResourceModel */ protected function _construct() { $this->_init('catalog_product_entity', 'entity_id'); // initialize table with it's primary key } /** * @return mixed */ protected function getMainTable() { return $this->getMainTable(); // catalog_product_entity } }
And this is our custom resource model we have created using small module extension. Cheers! Hope this helps you guys!