How to Create Model, Resource Model and Collection in Magento 2

Posted on 10 February, 2017

In this post, We'll explain you the usage of Model, Resource Model and Collection in Magento 2. After following few simple steps of this post, you are able to insert sample data on custom table and also display them on frontend.

We have already published 2 technical note for Magento 2, which are:

  1. How To Create a Magento 2 Module
  2. Create Custom Database Table in Magento 2

I hope you have understood and applied easily. In this post, we will go more deeper into the usage of Model, Resource Model and Collection in Magento 2. After this post, you are able to:

  1. Insert sample data on custom table.
  2. Create Model, Resource Model and Collection files.
  3. Get data from the custom table and display them on frontend.

Follow the simple steps which are listed on below.

1) Insert sample data on custom table.

Because we already installed Emipro_HelloWorld module as per our last technical note, we need to upgrade this module for insert few sample data.

Step 1: Create the upgrade data script file

We have already created the Setup folder at app/code/Emipro/HelloWorld/Setup. So, now we just need to create UpgradeData.php file at app/code/Emipro/HelloWorld/Setup/UpgradeData.php and paste below code into it. In this file will write a code for check the module version and insert few sample data into the custom table.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
  
namespace Emipro\HelloWorld\Setup;
  
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
  
class UpgradeData implements UpgradeDataInterface
{
    public function upgrade(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $setup->startSetup();
  
        if (version_compare($context->getVersion(), '1.0.1') < 0) {
            // Get emipro_sampletable table
            $tableName = $setup->getTable('emipro_sampletable');
            // Check if the table already exists
            if ($setup->getConnection()->isTableExists($tableName) == true) {
                // Declare data
                $data = [
                    [
                        'title' => 'Sample Title 1',
                        'summary' => 'Sample summary',
                        'description' => 'Sample description',
                        'created_at' => date('Y-m-d H:i:s'),
                        'status' => 1
                    ],
                    [
                        'title' => 'Sample Title 2',
                        'summary' => 'Sample summary',
                        'description' => 'Sample description',
                        'created_at' => date('Y-m-d H:i:s'),
                        'status' => 1
                    ]
                ];
  
                // Insert data to table
                foreach ($data as $item) {
                    $setup->getConnection()->insert($tableName, $item);
                }
            }
        }
  
        $setup->endSetup();
    }
}

Step 2: Modify the module.xml file

Open the module.xml file from app/code/Emipro/HelloWorld/etc/module.xml then modify setup_version="1.0.0" to setup_version="1.0.1".

1
2
3
4
5
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Emipro_HelloWorld" schema_version="1.0.1" setup_version="1.0.1">
    </module>
</config>

Step 3: Upgrade your module

Open Command line in folder root of magento and run both commands

php bin/magento setup:upgrade

php bin/magento cache:flush

For more informations about Magento 2 Useful Commands List Click Here and read our another technical note.

Now check your database and you will see few sample data successfully inserted on emipro_sampletable table.

If your module is not installed before, you can see the following way to insert the sample data to the custom table.

Create InstallData.php file at app/code/Emipro/HelloWorld/Setup/InstallData.php and paste below code into it. In this file will write a code for insert the sample data into the custom table when your module is installed.

Now, repeat the step 3 and see the result.

2) Create Model, Resource Model and Collection files.

Now you need to create some files for insert, update, delete and get data from the custom table. Before Creating files, you need to create appropriate folders if it’s doesn’t exist.

Create model Sample.php file at app/code/Emipro/HelloWorld/Model/Sample.php and paste this following code into it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
  
namespace Emipro\HelloWorld\Model;
  
use Magento\Framework\Model\AbstractModel;
  
class Sample extends AbstractModel
{
    /**
     * Define resource model
     */
    protected function _construct()
    {
        $this->_init('Emipro\HelloWorld\Model\ResourceModel\Sample');
    }
}

Create resource model Sample.php file at app/code/Emipro/HelloWorld/Model/ResourceModel/Sample.php and paste this following code into it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
  
namespace Emipro\HelloWorld\Model\ResourceModel;
  
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
  
class Sample extends AbstractDb
{
    /**
     * Define main table
     */
    protected function _construct()
    {
        $this->_init('emipro_sampletable', 'id');
    }
}

Create collection Collection.php file at app/code/Emipro/HelloWorld/Model/ResourceModel/Sample/Collection.php and paste this following code into it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
  
namespace Emipro\HelloWorld\Model\ResourceModel\Sample;
  
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
  
class Collection extends AbstractCollection
{
    /**
     * Define model & resource model
     */
    protected function _construct()
    {
        $this->_init(
            'Emipro\HelloWorld\Model\Sample',
            'Emipro\HelloWorld\Model\ResourceModel\Sample'
        );
    }
}

3. Get data from the custom table and display them on frontend.

As per our first article "How To Create a Magento 2 Module" you already created routes.xml file at app/code/Emipro/HelloWorld/etc/frontend/routes.xml. If you don't know about that file then please refer our article which is How To Create a Magento 2 Module.

Also we have already created Index.php at app/code/Emipro/HelloWorld/Controller/Index/Index.php. So, just open Index.php file and replace following code with it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
  
namespace Emipro\HelloWorld\Controller\Index;
  
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Emipro\HelloWorld\Model\SampleFactory;
  
class Index extends Action
{
    /**
     * @var \Emipro\HelloWorld\Model\SampleFactory
     */
    protected $_modelSampleFactory;
  
    /**
     * @param Context $context
     * @param SampleFactory $modelSampleFactory
     */
    public function __construct(
        Context $context,
        SampleFactory $modelSampleFactory
    ) {
        parent::__construct($context);
        $this->_modelSampleFactory = $modelSampleFactory;
    }
  
    public function execute()
    {
        $sampleModel = $this->_modelSampleFactory->create();
  
        // Load the item with ID is 1
        $item = $sampleModel->load(1);
        var_dump($item->getData());
  
        // Get sample collection
        $sampleCollection = $sampleModel->getCollection();
        // Load all data of collection
        var_dump($sampleCollection->getData());
    }
}

Open Command line in folder root of magento and run "php bin/magento cache:flush" command. Then run the following link http://domain.com/helloworld/index/index, and see the result.

I hope this Magento technical note helped you to understand the usage of Model, Resource Model and Collection in Magento 2. Bookmark it for your future reference. Do comment below if you have any other questions or doubts.

P.S. Do share this note with your team.


Mayank Zalavadia , eCommerce Project Manager
Magento Technical Notes

Post Your Review

X

Your Review has been posted

0 Comment(s)