Working with Models in Magento 2

This is part 2 of two parts article. See part 1 by clicking here.

This article is part 2 of “Working with Magento 2 Models”, which is talking about Model class file creation in Magento 2 and fetching data from database table using same. To see part 1 click on Creating Setup script in Magento 2.Goal of this article is to fetch data from database table

Important elements of using Models in Magento 2

Models are basically used to interact with Database.In this article we will see how to use Models to fetch data from database tables in Magento 2. Be careful, none of the class under model creation should not contain SQL directly.

In Magento 2 Models has three parts :-

  • Model Interface :- It’s an interface that creates setter, which is used to geter, setter methods for all the db fields. These methods are used for API related functionality.
  • Model : Models implement the Model Interface and it calls the Resource Model . It also uses caching tag and event prefix.
  • ResourceModel: It is used to contain overall database logic, it do not execute sql queries. It has two parts
    • ResourceModel
    • Collection

Lets see example of each section.

Creating Model Interface in Magento 2

File Path: app\code\Cutehits\First\Model\Api\Data\CustomuserInterface.php


<?php
namespace Cutehits\First\Model\Api\Data;
interface CustomuserInterface
{

}

Code Analysis: Since we are not looking for any API functionality into this tutorial so this class doesn’t contain anything.

Creating Model Class in Magento 2

File Path: app\code\Cutehits\First\Model\Customuser.php


<?php
namespace Cutehits\First\Model;
class Customuser extends \Magento\Framework\Model\AbstractModel implements \Magento\Framework\DataObject\IdentityInterface,
\Cutehits\First\Model\Api\Data\CustomuserInterface
{
const CACHE_TAG = 'cutehits_first_user';

protected $_cacheTag = 'cutehits_first_user';

protected $_eventPrefix = 'cutehits_first_user';

protected function _construct()
{
$this->_init('Cutehits\First\Model\ResourceModel\Customuser');
}

public function getIdentities()
{
return [self::CACHE_TAG . '_' . $this->getId()];
}

public function getDefaultValues()
{
$values = [];

return $values;
}
}

Code Analysis:
This model class will extends AbstractModel class Magento\Framework\Model\AbstractModel which further implements PostInterface and IdentityInterface \Magento\Framework\DataObject\IdentityInterface. The IdentityInterface will force Model class define the getIdentities() method that will return a unique id for each model. Main requirement of this interface is to provide unique id so in case your model required cache refresh after database operation and render information to the frontend page, then you must use this.

Next important part of this model class is its _construct() method. Which further calls _init() method. This _init() method will define the resource model which will actually fetch the information from the database. As above, we define the resource model Cutehits\First\Model\ResourceModel\Customuser . Another important part is some variable which you should you in your model:

  • $_eventPrefix – a prefix for events to be triggered
  • $_eventObject – a object name when access in event
  • $_cacheTag – a unique identifier for use within caching

Creating ResourceModel Class in Magento 2

As above ResourceModel has two parts:

a) ResourceModel: It has below code


<?php
namespace Cutehits\First\Model\ResourceModel;

class Customuser extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
/**
* Date model
*
* @var \Magento\Framework\Stdlib\DateTime\DateTime
*/
protected $_date;

/**
* constructor
*
* @param \Magento\Framework\Stdlib\DateTime\DateTime $date
* @param \Magento\Framework\Model\ResourceModel\Db\Context $context
*/
public function __construct(
\Magento\Framework\Stdlib\DateTime\DateTime $date,
\Magento\Framework\Model\ResourceModel\Db\Context $context
)
{
$this->_date = $date;
parent::__construct($context);
}

/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init('cutehits_custom_users', 'user_id');
}

/**
* before save callback
*
* @param \Magento\Framework\Model\AbstractModel|\Mageplaza\HelloWorld\Model\Post $object
* @return $this
*/
protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
{
$object->setUpdatedAt($this->_date->date());
if ($object->isObjectNew()) {
$object->setCreatedAt($this->_date->date());
}
return parent::_beforeSave($object);
}
}

Code Analysis: It has a constructor call and one hook calls. There are multiple hook methods can be implemented

  • afterLoad()
  • beforeSave()
  • afterSave()
  • beforeDelete()
  • afterDelete()
  • afterCommitCallback()
  • deleteCommit()

b) Collection.php

File: app\code\Cutehits\First\Model\ResourceModel\Customuser\Collection.php


<?php
namespace Cutehits\First\Model\ResourceModel\Customuser;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected $_idFieldName = 'user_id';
protected $_eventPrefix = 'cutehits_custom_users_collection';
protected $_eventObject = 'customusers_collection';

/**
* Define resource model
*
* @return void
*/
protected function _construct()
{
$this-&gt;_init('Cutehits\First\Model\Customuser', 'Cutehits\First\Model\ResourceModel\Customuser');
}

/**
* Get SQL for get record count.
* Extra GROUP BY strip added.
*
* @return \Magento\Framework\DB\Select
*/
public function getSelectCountSql()
{
$countSelect = parent::getSelectCountSql();
$countSelect-&gt;reset(\Zend_Db_Select::GROUP);
return $countSelect;
}
/**
* @param string $valueField
* @param string $labelField
* @param array $additional
* @return array
*/
protected function _toOptionArray($valueField = 'user_id', $labelField = 'name', $additional = [])
{
return parent::_toOptionArray($valueField, $labelField, $additional);
}
}
The following two tabs change content below.

Chandra Shekhar

GCP Architect
Chandra Shekhar Pandey is Google certified Cloud engineer, I am Magento2 Trained developer. Having huge experience in designing cloud solution. I have around 12 years of experience with world enterprise IT companies and fortune 500 clients. During my architecture design I am always caring about high availability, fast performance and resilient system. From the programmer background I have huge experience in LAMP stack as well. Throughout my carrier I have worked on Retail, E-Learning, Video Conferencing and social media domain. The motive of creating cutehits was just to share the knowledge/solutions I get to know during my day to day life so that if possible I can help someone for same problems/solutions. CuteHits.com is a really a very effort for sharing knowledge to rest of the world. For any query/suggestion about same you can contact me on below details:- Email: shekharmca2005 at gmail.com Phone: +91-9560201363

Latest posts by Chandra Shekhar (see all)

You may also like...