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\Cozmot\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 Cozmot\Extension\Model;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Extension extends AbstractModel
{
protected function _construct()
{
$this->_init(‘Cozmot\Extension\Model\ResourceModel\Extension’);
}
}
|
Create file app\code\Cozmot\Extension\Model\ResourceModel\Extension.php
1
2
3
4
5
6
7
8
9
10
11
|
<?php
namespace Cozmot\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 Cozmot\Extension\Model\ResourceModel\Extension;
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected function _construct()
{
$this->_init(‘Cozmot\Extension\Model\Extension’, ‘Cozmot\Extension\Model\ResourceModel\Extension’);
}
}
|
Done!
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.
[/et_pb_text][/et_pb_column][/et_pb_row][/et_pb_section]]]>