How to Create Model File to Perform CRUD Operation in Magento 2
In the previous tutorial, you came to know how to create a table in Magento 2. This tutorial is all about creating a model file to perform CRUD operation.
To use a table in Magento, one has to create files for the model.
Bookmark this tutorial while developing a Magento 2 module.
Steps to Create Model File to Perform CRUD Operation in Magento 2:
Create a file having a name Extension.php in given address: app\code\Meetanshi\Extension\Model
The name of the table is Extension here so we have given the name of a file Extension.php.
For fetching and loading the data, you need to create another file “Extension.php” on a given location.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php namespace Meetanshi\Extension\Model; use Magento\Framework\Model\AbstractModel; use Magento\Framework\Model\ResourceModel\Db\AbstractDb; class Extension extends AbstractModel { protected function _construct() { $this->_init('Meetanshi\Extension\Model\ResourceModel\Extension'); } } |
Create file app\code\Meetanshi\Extension\Model\ResourceModel\Extension.php
1 2 3 4 5 6 7 8 9 10 11 |
<?php namespace Meetanshi\Extension\Model\ResourceModel; use Magento\Framework\Model\ResourceModel\Db\AbstractDb; class Extension extends AbstractDb { protected function _construct() { $this->_init('extension', 'id'); } } |
Another important file is Collection.php
Collection.php file helps to collect all the data of the table.
In the given path, create a file and copy the code.
app\code\Extension\Model\ResourceModel\Extension\Collection.php
1 2 3 4 5 6 7 8 9 10 |
<?php namespace Meetanshi\Extension\Model\ResourceModel\Extension; class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection { protected function _construct() { $this->_init('Meetanshi\Extension\Model\Extension', 'Meetanshi\Extension\Model\ResourceModel\Extension'); } } |
Done!
Note, For instance, you need to send data from other platforms’ registration forms to the Magento database or integrate API in mobile. For such requirements, we have to call an API that sends a request to the server. In such scenarios, use the code to perform CRUD operation using API in Magento 2!
I would be happy to answer your questions regarding this blog.
Please do consider sharing this blog with interested ones via social media.
Thanks a bunch.
Jignesh Parmar
An expert in his field, Jignesh is the team leader at Meetanshi and a certified Magento developer. His passion for Magento has inspired others in the team too. Apart from work, he is a cricket lover.
Prev
We are 3 Now – A Recap of Meetanshiversary Party
How to Save Form Data to the Custom Table in Magento 2
Next