Magento 2 create custom model
Every custom module that need to interact with database for that we need to create model. So today we talk about how to create magento 2 create custom model. Model consist of three files model file, resource model file and collection. So let create the our model file.
Step 1: Model file
Model file is pointing out our resource model. Here is example code model file on Github.
<?php
namespace QaisarSatti\HelloWorld\Model;
class Helloworld extends \Magento\Framework\Model\AbstractModel
{
protected function _construct()
{
$this->_init('QaisarSatti\HelloWorld\Model\ResourceModel\Helloworld');
}
}
namespace QaisarSatti\HelloWorld\Model;
class Helloworld extends \Magento\Framework\Model\AbstractModel
{
protected function _construct()
{
$this->_init('QaisarSatti\HelloWorld\Model\ResourceModel\Helloworld');
}
}
Step 2: Create Resource model file
In resource model file we initialize table name and primary key column name. Here is example code resource model file on Github.
<?php
namespace QaisarSatti\HelloWorld\Model\ResourceModel;
use \Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Helloworld extends AbstractDb
{
protected function _construct()
{
$this->_init('blog_posts', 'post_id');
}
}
namespace QaisarSatti\HelloWorld\Model\ResourceModel;
use \Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Helloworld extends AbstractDb
{
protected function _construct()
{
$this->_init('blog_posts', 'post_id');
}
}
Step 3: Collection model
In collection model file have initialize model and resource model. Here is example code collection model file on Github.
<?php
namespace QaisarSatti\HelloWorld\Model\ResourceModel\Helloworld;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected function _construct()
{
$this->_init(
'QaisarSatti\HelloWorld\Model\Helloworld',
'QaisarSatti\HelloWorld\Model\ResourceModel\Helloworld');
}
}
namespace QaisarSatti\HelloWorld\Model\ResourceModel\Helloworld;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected function _construct()
{
$this->_init(
'QaisarSatti\HelloWorld\Model\Helloworld',
'QaisarSatti\HelloWorld\Model\ResourceModel\Helloworld');
}
}
Here is complete example code on Github