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');
        }
    }

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');

    }

}

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');

    }

}

Here is complete example code on Github

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply