Create a Magento2 model and database

This tutorial is the 6th in a long series of magento2 tutorial. It will be updated little by little and with the evolutions of the platform. You will now create a Model to interact with the magento2 database. If you do not know magento (v1) it does not matter, I will speak of it but it is not necessary to know the magento platform (v1) to master this tutorial on magento2.

In the previous tutorial we saw how to add a module to the administration part (backend) of magento2! We will now see the way to interact with the database. For that, we will start from the files of our previous tutorial.

Create Model

The template is the class that will allow you to interact easily with your database. The contact class "Contact" with its methods. Be careful, this class should not contain SQL directly.
Create a Model directory at the root of your module (Pfay/Contacts/Model) and add the Contact.php file with the following content:

<?php

namespace Pfay\Contacts\Model;

use Magento\Cron\Exception;
use Magento\Framework\Model\AbstractModel;

/**
 * Contact Model
 *
 * @author      Pierre FAY
 */
class Contact extends AbstractModel
{
    /**
     * @var \Magento\Framework\Stdlib\DateTime
     */
    protected $_dateTime;

    /**
     * @return void
     */
    protected function _construct()
    {
        $this->_init(\Pfay\Contacts\Model\ResourceModel\Contact::class);
    }
    
}

You will notice that in the constructor, the model class will call the ResourceModel class

Create ResourceModel

The resourceModel is the class that allows you to "store" your SQL queries, it is used by the model to interract in sql with the database. Create in your Template folder a ResourceModel folder with a Contact.php class that will contain the following code:

<?php

namespace Pfay\Contacts\Model\ResourceModel;

use Magento\Framework\Model\ResourceModel\Db\AbstractDb;

/**
 * Contact Resource Model
 *
 * @author      Pierre FAY
 */
class Contact extends AbstractDb
{
    /**
     * Initialize resource
     *
     * @return void
     */
    public function _construct()
    {
        $this->_init('pfay_contacts', 'pfay_contacts_id');
    }
}

pfay_contacts is the name of the pfay_contacts table we created in the previous Magento2 Installer tutorial, and pfay_contacts_id is the primary key to this table.

Create Collection

Let's create the collection now. A collection, ie you have the ability to search multiple objects in the database. Basically if you create a collection of objects then you add filters that will let you load only certain objects from your table. We will come back to this later.

In the ResourceModel folder, create the Contact folder and in this folder, the Collection.php

<?php

namespace Pfay\Contacts\Model\ResourceModel\Contact;

use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;

/**
 * Contact Resource Model Collection
 *
 * @author      Pierre FAY
 */
class Collection extends AbstractCollection
{
    /**
     * Initialize resource collection
     *
     * @return void
     */
    public function _construct()
    {
        $this->_init('Pfay\Contacts\Model\Contact', 'Pfay\Contacts\Model\ResourceModel\Contact');
    }
}

Create a contact from the Model

To test all this, go into our Index action, located in the Pfay\Contacts\Controller\Test namespace. Edit this file as follows:

<?php

namespace Pfay\Contacts\Controller\Test;

class Index extends \Magento\Framework\App\Action\Action
{
    public function execute()
    {
        $contact = $this->_objectManager->create('Pfay\Contacts\Model\Contact');
        $contact->setName('Paul Dupond');
        $contact->save();
        die('test');
    }
}

The extended class\Magento\Framework\App\Action\Action that contains the _objectManager object that will let you instantiate your Model. So you instantiate your Model Contact, set a name with setName, and save it with the save() method.
If I had a "toto" property, I would setToto('my_value'). In short you understand the principle ;)

Then visit the url www.magento2.lan/index.php/contacts/test. You should see a blank page with "test" written on it.

Creating objects

I change the code to add several contacts:

<?php
namespace Pfay\Contacts\Controller\Test;

use Magento\Framework\App\Action\Action;

class Index extends Action
{
    public function execute()
    {
        $contact = $this->_objectManager->create('Pfay\Contacts\Model\Contact');
        $contact->setName('Paul Dupond');
        $contact->save();

        $contact = $this->_objectManager->create('Pfay\Contacts\Model\Contact');
        $contact->setName('Paul Ricard');
        $contact->save();

        $contact = $this->_objectManager->create('Pfay\Contacts\Model\Contact');
        $contact->setName('Jack Daniels');
        $contact->save();
        die('test');
    }
}

Visit the page and hop your 3 Contacts have been added! Then go to your database and you will see that your contact Dupond, Ricard or even that good old Jack was added well ;)

mysql> select * from pfay_contacts;
+------------------+--------------+--------+---------+
| pfay_contacts_id | name         | email  | comment |
+------------------+--------------+--------+---------+
|                1 | Paul Dupond  | simple | 0       |
|                2 | Paul Ricard  | simple | 0       |
|                3 | Jack Daniels | simple | 0       |
+------------------+--------------+--------+---------+
3 rows in set (0.00 sec)

Playing with magento2 collections

I still change the code of my controller to do the test:

namespace Pfay\Contacts\Controller\Test;

class Index extends \Magento\Framework\App\Action\Action
{
    public function execute()
    {
        $contactModel = $this->_objectManager->create('Pfay\Contacts\Model\Contact');
        $collection = $contactModel->getCollection()->addFieldToFilter('name', array('like'=> 'Paul Ricard'));
        foreach($collection as $contact) {
            var_dump($contact->getData());
        }        
        die('test');
    }
}
This time I retrieve the Contact object collection from the getCollection() method, I filter on the name with the addFieldToFilter() method to retrieve it as contact type objects with a "Paul Ricard" name, and I go through my collection to see the results.

There you go ! This is already the end of this tutorial. Does not it work for you? Retrieve the sources of this module at the bottom of this article and find out more easily your error.

You can add a Model, a ResourceModel, and a collection to your magento2 project to translate to the database. We will go into more detail in the database operation and comment on interacting with in a next lesson.

If you liked this tutorial, please thank me in 1 click by sharing this article on twitter, googleplus or facebook, it may seem useless but for me it is very important. Thank you to those who will do it;) Do not hesitate to ask your questions in the comments, I will try to answer quickly.
Good luck to all for the continuation of these tutorials on magento2!
Available documents for this article :
Books that can help you :
  • Livre Magento 2 Developer's Guide by Branko
  • Livre Mastering Magento2 Second Edition
  • Livre Magento 2 Cookbook
Questions about this lesson
No questions for this lesson. Be the first !

You must be logged in to ask for help on a lesson.