meta charset='UTF-8'/> CRUD Models in Magento 2 | Magento 2 Store
Rated 5/5 based on 100 votes

CRUD Models in Magento 2

magento 2 get collection

CRUD Models in Magento 2 can manage data in database easily, you don’t need to write many line of code to create a CRUD. CRUD is stand for Create, Read, Update and Delete. We will learn about some main contents: How to setup Database, Model, Resource Model and Resource Magento 2 Get Collection and do database related operations. In previous topic, we discussed about Creating Hello World Module
Before learning this topic, let’s decide how the table which we work with will look. I will create a table mageplaza_topic and take the following columns:
  • topic_id - the topic unique identifier
  • title - the title of the topic
  • content - the content of the topic
  • creation_time - the date created

To create Model in Magento 2

  • Step 1: Setup Script
  • Step 2: Model
  • Step 3: Resource Model
  • Step 4: Resource Model Collection
  • Step 5: Factory Object

Step 1: Setup Script

Firstly, we will create database table for our CRUD models. To do this we need to insert the setup file:
app/code/Mageplaza/HelloWorld/Setup/InstallSchema.php
This file will execute only one time when install the module. Let put this content for this file to create above table:
namespace Mageplaza\HelloWorld\Setup;
class InstallSchema implements \Magento\Framework\Setup\InstallSchemaInterface
{
    public function install(
        \Magento\Framework\Setup\SchemaSetupInterface $setup,
        \Magento\Framework\Setup\ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();
        $table = $installer->getConnection()->newTable(
            $installer->getTable('mageplaza_topic')
        )->addColumn(
            'topic_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
            null,
            ['identity' => true, 'nullable' => false, 'primary' => true, 'unsigned' => true],
            'Topic ID'
        )->addColumn(
            'title',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            ['nullable' => false],
            'Topic Title'
        )->addColumn(
            'content',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            '2M',
            [],
            'Topic Content'
        )->addColumn(
            'creation_time',
            \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
            null,
            ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
            'Topic Creation Time'
        )->setComment(
            'Mageplaza Topic Table'
        );
        $installer->getConnection()->createTable($table);
        $installer->endSetup();
    }
}
This content is showing how the table created, you can edit it to make your own table. Please note that Magento will automatically run this file for the first time when installing the module. If you installed the module before, you will need to upgrade module and write the table create code to the UpgradeSchema.php in that folder.
After this please run this command line:
php bin/magento setup:upgrade
Now checking your database, you will see a table with name ‘mageplaza_topic’ and above columns. If this table is not created, it may be because you ran the above command line before you add content to InstallSchema.php. To fix this, you need remove the information that let Magento know your module has installed in the system. Please open the table ‘setup_module’, find and remove a row has module equals to ‘mageplaza_topic’. After this, run the command again to install the table.
This InstallSchema.php is used to create database structure. If you want to install the data to the table which you was created, you need to use InstallData.phpfile:
app/code/Mageplaza/HelloWorld/Setup/InstallData.php
Please take a look in some InstallData file in Magento to know how to use it. This’s some file you can see:
- vendor/magento/module-tax/Setup/InstallData.php
- vendor/magento/module-customer/Setup/InstallData.php
- vendor/magento/module-catalog/Setup/InstallData.php
As I said above, those install file will be used for first time install the module. If you want to change the database when upgrade module, please try to useUpgradeSchema.php and UpgradeData.php.

Step 2: Model

Model is a huge path of MVC architecture. In Magento 2 CRUD, models have many different functions such as manage data, install or upgrade module. In this tutorial, I only talk about data management CRUD. We have to create Model, Resource Model, Resource Model Conllection to manage data in table: mageplaza_topic as I mentioned above.
Before create model, we need to create the interface for it. Let create the TopicInterface:
app/code/Mageplaza/HelloWorld/Model/Api/Data/TopicInterface.php
And put this content:
<?php
namespace Mageplaza\HelloWorld\Model\Api\Data;
interface TopicInterface
{
 public function getId();
 public function setId();
 
 public function getTitle();
 public function setTitle();
 
 public function getContent();
 public function setContent();
 
 public function getCreationTime();
 public function setCreationTime();
}
This interface has defined the set and get method to table data which we would use when interacting with the model. This interface plays an important role when it comes time to exporting CRUD models to Magento service contracts based API.
Now we will create the model file:
app/code/Mageplaza/HelloWorld/Model/Topic.php
And this is the content of that file:
<?php 
namespace Mageplaza\HelloWorld\Model;
class Topic extends \Magento\Framework\Model\AbstractModel implements \Magento\Framework\DataObject\IdentityInterface,
\Mageplaza\HelloWorld\Model\Api\Data\TopicInterface
{
 const CACHE_TAG = 'mageplaza_topic';

 protected function _construct()
 {
  $this->_init('Mageplaza\HelloWorld\Model\ResourceModel\Topic');
 }

 public function getIdentities()
 {
  return [self::CACHE_TAG . '_' . $this->getId()];
 }
}
This model class will extends AbstractModel class Magento\Framework\Model\AbstractModel and implements TopicInterface and IdentityInterface\Magento\Framework\DataObject\IdentityInterface. The IdentityInterface will force Model class define the getIdentities() method which will return a unique id for the model. You must only use this interface if your model required cache refresh after database operation and render information to the frontend page.
The _construct() method will be called whenever a model is instantiated. Every CRUD model have to use the _construct() method to call _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 Mageplaza\Topic\Model\ResourceModel\Topic The last thing about model 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

Step 3: Resource Model

As you know, the model file contain overall database logic, it do not execute sql queries. The resource model will do that. Now we will create the Resource Model for this table: Mageplaza\HelloWorld\Model\ResourceModel\Topic
Content for this file:
<?php
namespace Mageplaza\HelloWorld\Model\ResourceModel;
class Topic extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
 protected function _construct()
 {
  $this->_init('mageplaza_topic', 'topic_id');
 }
}
Every CRUD resource model in Magento must extends abstract class \Magento\Framework\Model\ResourceModel\Db\AbstractDb which contain the functions for fetching information from database.
Like model class, this resource model class will have required method _construct(). This method will call _init() function to define the table name and primary key for that table. In this example, we have table ‘mageplaza_topic’ and the primary key ‘topic_id’.

Step 4: Resource Model Collection - Get Model Collection

The collection model is considered a resource model which allow us to filter and fetch a collection table data. The collection model will be placed in:
Mageplaza\HelloWorld\Model\ResourceModel\Topic\Collection.php
The content for this file:
<?php
namespace Mageplaza\HelloWorld\Model\ResourceModel\Topic;
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
 protected function _construct()
 {
  $this->_init('Mageplaza\HelloWorld\Model\Topic', 'Mageplaza\HelloWorld\Model\ResourceModel\Topic');
 }
}
The CRUD collection class must extends from \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection and call the _init() method to init the model, resource model in _construct() function.

Step 5: Factory Object

We are done with creating the database table, CRUD model, resource model and collection. So how to use them?
In this part, we will talk about Factory Object for model. As you know in OOP, a factory method will be used to instantiate an object. In Magento, the Factory Object do the same thing.
The Factory class name is the name of Model class and append with the ‘Factory’ word. So for our example, we will have TopicFactory class. You must not create this class. Magento will create it for you. Whenever Magento’s object manager encounters a class name that ends in the word ‘Factory’, it will automatically generate the Factory class in the var/generation folder if the class does not already exist. You will see the factory class in
var/generation/<vendor_name>/<module_name>/Model/ClassFactory.php
To instantiate a model object we will use automatic constructor dependency injection to inject a factory object, then use factory object to instantiate the model object.
For example, we will call the model to get data in Block. We will create a Topic block:
Mageplaza\HelloWorld\Block\Topic.php
Content for this file:
<?php
namespace Mageplaza\HelloWorld\Block;
class Topic extends \Magento\Framework\View\Element\Template
{
 protected $_topicFactory;
 public function _construct(
  \Magento\Framework\View\Element\Template\Context $context,
  \Mageplaza\HelloWorld\Model\TopicFactory $topicFactory
 ){
  $this->_topicFactory = $topicFactory;
  parent::_construct($context);
 }

 public function _prepareLayout()
 {
  $topic = $this->_topicFactory->create();
  $collection = $topic->getCollection();
  foreach($collection as $item){
   var_dump($item->getData());
  }
  exit;
 }
}
As you see in this block, the TopicFactory object will be created in the _construct() function. In the _prepareLayout() function, we use $topic = $this->_topicFactory->create(); to create the model object.
People also searched for:



Share on Google Plus

About Hoàng Kang

Name: Nguyễn Tuấn Hoàng

 photo 1f451_zpsp5spiubu.png If you're good at something, never do it for free  photo 1f451_zpsp5spiubu.png

    Blogger Comment
    Facebook Comment

1 comments: