Magento 2: Models, Resource Models, And Collections
In this topic, we will discuss about Create resource model in Magento 2. In previous topic, we have discussed about CRUD and models.
As you know, the model file contain overall database logic, it do not execute sql queries. The resource model will do that. Now we will create the Resource Model for this table:
Mageplaza\HelloWorld\Model\ResourceModel\Topic
Resource Model
Content for this file:
<?php
namespace Mageplaza\HelloWorld\Model\ResourceModel;
class Topic extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
protected function _construct()
{
$this->_init('mageplaza_topic', 'topic_id');
}
}
Every CRUD resource model in Magento must extends abstract class \Magento\Framework\Model\ResourceModel\Db\AbstractDb
which contain the functions for fetching information from database.
Like model class, this resource model class will have required method _construct()
. This method will call _init()
function to define the table name and primary key for that table. In this example, we have table ‘mageplaza_topic’ and the primary key ‘topic_id’.
Resource Model Collection - Get Model Collection
The collection model is considered a resource model which allow us to filter and fetch a collection table data. The collection model will be placed in:
Mageplaza\HelloWorld\Model\ResourceModel\Topic\Collection.php
The content for this file:
<?php
namespace Mageplaza\HelloWorld\Model\ResourceModel\Topic;
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected function _construct()
{
$this->_init('Mageplaza\HelloWorld\Model\Topic', 'Mageplaza\HelloWorld\Model\ResourceModel\Topic');
}
}
The CRUD collection class must extends from \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
and call the _init()
method to init the model, resource model in _construct()
function.
- How to create a simple Hello World module for Magento 2
- Magento 2 Block Template Ultimate Guides
- How to Create Module in Magento 2
- How to Create Controller in Magento 2
- How to create CRUD Models in Magento 2
- How to Create Magento 2 Block, Layout and Templates
- Configuration - System.xml
- How To Create Admin Menu In Magento 2
- Admin ACL
- Admin Grid
People also searched for
- magento 2 create resource model
- create resource model in magento 2
- 2.3.x, 2.4.x