Hello Everyone,
In this blog, we will learn about how to Create Model, Resource Model and Collection file in Magento 2.
If we went to perform CRUD operations i.e. CREATE, READ, UPDATE, DELETE then we need to create these three files.
Without wasting your time, let us guide you straight away. Follow the easy step given below to Create a Model, Resource Model and Collection in Magento 2.
STEPS FOR CREATE MODEL, RESOURCE MODEL AND COLLECTION IN MAGENTO 2
Model:
Model represents a single row of the table. The model will use a resource model to get or set data.
Now we create a Model file.
Step 1: Create model file BookInfo.php
app/code/Vendor/Extension/Model/BookInfo.php
<?php
namespace Vendor\Extension\Model;
use Vendor\Extension\Model\ResourceModel\BookInfo as BookInfoResourceModel;
use Magento\Framework\Model\AbstractModel;
class BookInfo extends AbstractModel
{
protected function _construct()
{
$this->_init(BookInfo ResourceModel::class);
}
}
Resource Model:
Every model must have a resource model. All database operations are performed using the resource model.
Step 2: Create Resource Model file BookInfo.php
app/code/Vendor/Extension/Model/ResourceModel/BookInfo.php
<?php
namespace Vendor\Extension\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class BookInfo extends AbstractDb
{
protected function _construct()
{
$this->_init('magecurious_custom_table', 'id');
}
}
Collection:
Collections have access to all or multiple rows of table. If we want to perform some filter or some sorting collection will be used.
Step 3: Create Collection file Collection.php
app/code/Vendor/Extension/Model/ResourceModel/BookInfo/Collection.php
<?php
namespace Vendor\Extension\Model\ResourceModel\BookInfo;
use Vendor\Extension\Model\BookInfo as BookInfoModel;
use Vendor\Extension\Model\ResourceModel\BookInfo as BookInfoResourceModel;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected function _construct()
{
$this->_init(
BookInfoModel::class,
BookInfo ResourceModel::class
);
}
}
Step 4: Finally run the below commands.
$ php bin/magento setup:upgrade
$ php bin/magento cache:clean
$ php bin/magento cache:flush
Final Thoughts:
So this was the easiest way which we have told you in this blog. This is how you can Create Model, Resource Model and Collection in Magento 2. Hope you liked the blog.
So quickly go to the comment box and tell me how you like this blog?
Stay tuned with us on our site to get new updates of Magento.
Thanks for reading and visiting our site.
