How to use Model in Magento 2 extension

Model in Magento 2 is an importance knowledge with Magento Developer because you have to get , insert, update, delete data . I have introduce How to add new Table to Database in Magento 2 extension in previous post so I will introduce How to use Model in Magento 2 in this post. I hope the post will useful for you when Building Mageto 2 extension. You can check posts in this tutorial
if you are confusing about how to Build Magento 2 extension.

To Use Model :
1. Create Model.
2 . Get Data
3. Insert , Update, Delete
I will crate model with name is Posts.


Step 1 : Create Model

  • Create File app/code/Magebay/Hello/Model/Posts.
<?php
namespace Magebay\Hello\Model;
use Magento\Framework\Model\AbstractModel;

/**
 * Class Posts
 * @package Magebay\Hello\Model
 */
class Posts extends AbstractModel
{
    protected function _construct()
    {
        $this->_init('Magebay\Hello\Model\ResourceModel\Posts');
    }
}
  • Create file app/code/Magebay/Hello/Model\ResourceModel/Posts
<?php
namespace Magebay\Hello\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;

/**
 * Class Posts
 * @package Magebay\Hello\Model\ResourceModel
 */
class Posts extends AbstractDb
{
    protected function _construct()
    {
        // magebay_news is table name, news_id is Primary of Table
        $this->_init('magebay_news', 'news_id');
    }
}
  • Create file
    app/code/Magebay/Hello/Model\ResourceModel/Posts/Collection.php
<?php
namespace Magebay\Hello\Model\ResourceModel\Posts;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;

/**
 * Class Collection
 * @package Magebay\Hello\Model\ResourceModel\Posts
 */
class Collection extends AbstractCollection
{
    /**
     * Define model &amp; resource model
     */
    protected function _construct()
    {
        $this->_init(
            'Magebay\Hello\Model\Posts',
            'Magebay\Hello\Model\ResourceModel\Posts'
        );
    }
}

Step 2 : Get data

To testing modem you can add some items to table before testing and you can fast test on Controller because it more simple for you.

Edit file app/code/Magebay/Hello/Controller/Index/index.php

<?php
namespace Magebay\Hello\Controller\Index;
 
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

/**
 * Class Index
 * @package Magebay\Hello\Controller\Index
 */
class Index extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magebay\Hello\Model\ResourceModel\Posts\CollectionFactory
     */
    protected $postsFactory;

    /**
     * Index constructor.
     * @param Context $context
     * @param PageFactory $resultPageFactory
     * @param \Magebay\Hello\Model\ResourceModel\Posts\CollectionFactory $postsFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
		\Magebay\Hello\Model\ResourceModel\Posts\CollectionFactory $postsFactory
    )
    {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
        $this->postsFactory = $postsFactory;
		
    }

    /**
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
     */
    public function execute()
    {
		echo "Test Get Data ";
		$this->postsFactory->create();
		$collection = $this->postsFactory->create()
            ->addFieldToSelect(array('title','created_at','status','position')) // fields to select
            ->addFieldToFilter('status',1) // filter status = 1
            ->setPageSize(10) // get 10 items
            ->setOrder('position','ASC'); // order by position
		echo '<pre>';
		    print_r($collection->getData());
		echo '<pre>';

    }
}
 

Note: Remove generated/code/Magebay* you will see result when accessing to controller on link example.com/hello/index/index

Step 3: insert , update, delete data.

  • insert data .
    Create new file app/code/Magebay/Hello/Controller/Index/AddPost.php
<?php
namespace Magebay\Hello\Controller\Index;
 
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

/**
 * Class AddPost
 * @package Magebay\Hello\Controller\Index
 */
class AddPost extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magebay\Hello\Model\PostsFactory
     */
    protected $postsFactory;
    /**
     * @var \Magebay\Hello\Model\ResourceModel\PostsFactory
     */
    protected $resPostsFactory;

    /**
     * AddPost constructor.
     * @param Context $context
     * @param PageFactory $resultPageFactory
     * @param \Magebay\Hello\Model\PostsFactory $postsFactory
     * @param \Magebay\Hello\Model\ResourceModel\PostsFactory $resPostsFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
		\Magebay\Hello\Model\PostsFactory $postsFactory,
		\Magebay\Hello\Model\ResourceModel\PostsFactory $resPostsFactory
    )
    {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
        $this->postsFactory = $postsFactory;
        $this->resPostsFactory = $resPostsFactory;

    }

    /**
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
     */
    public function execute()
    {
        // data insert
        $newItem = array(
            'title'=>'We are building Magento PWA ',
            'status'=>1,
            'description'=>'We are building Magento PWA ',
            'position'=>3,
            'created_at'=>date('Y-m-d H:i:s')
        );
        $postModel = $this->postsFactory->create();
        $postModel->setData($newItem);
        try {
            $this->resPostsFactory->create()->save($postModel);
            echo "New post Id is ". $postModel->getId();
        }
        catch (\Exception $exception)
        {
            echo $exception->getMessage();
        }
    }
}
 

Go to yourdomain/hello/index/addPost and see result. Don’t forget clear cache when creating new controller .

You will see new post added in index controller .( get Data)
Go to yourdomain/hello/index/index

  • Update Data : Create file app/code/Magebay/Hello/Controller/Index/UpdatePost.php
<?php
/**
 * Created by PhpStorm.
 * User: maiuoc
 * Date: 2019-01-19
 * Time: 1:16 PM
 */

namespace Magebay\Hello\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

/**
 * Class UpdatePost
 * @package Magebay\Hello\Controller\Index
 */
class UpdatePost extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magebay\Hello\Model\PostsFactory
     */
    protected $postsFactory;
    /**
     * @var \Magebay\Hello\Model\ResourceModel\PostsFactory
     */
    protected $resPostsFactory;

    /**
     * UpdatePost constructor.
     * @param Context $context
     * @param PageFactory $resultPageFactory
     * @param \Magebay\Hello\Model\PostsFactory $postsFactory
     * @param \Magebay\Hello\Model\ResourceModel\PostsFactory $resPostsFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        \Magebay\Hello\Model\PostsFactory $postsFactory,
        \Magebay\Hello\Model\ResourceModel\PostsFactory $resPostsFactory
    )
    {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
        $this->postsFactory = $postsFactory;
        $this->resPostsFactory = $resPostsFactory;

    }

    /**
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
     */
    public function execute()
    {
        $postId = 3; // post Id
        //Create array data update
        $updateItem = array(
            'title'=>'We are building Magento PWA Studio',
            'status'=>1,
            'description'=>'We are building Magento PWA Studio',
            'position'=>1,
        );
        $postModel = $this->postsFactory->create();

        try {
            $postModel->setData($updateItem)->setId($postId);
            $this->resPostsFactory->create()->save($postModel);
            echo "Update Item  ". $postModel->getId();
        }
        catch (\Exception $exception)
        {
            echo $exception->getMessage();
        }
    }
}

Access to link yourdomain/hello/index/updatePost to see result.

if you back to getting data controller to changing result.


  • Delete Database. Create fill DellPost.php in app/code/Magebay/Hello/Controller/Index/
<?php
/**
 * Created by PhpStorm.
 * User: maiuoc
 * Date: 2019-01-19
 * Time: 1:16 PM
 */

namespace Magebay\Hello\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

/**
 * Class DellPost
 * @package Magebay\Hello\Controller\Index
 */
class DellPost extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magebay\Hello\Model\PostsFactory
     */
    protected $postsFactory;
    /**
     * @var \Magebay\Hello\Model\ResourceModel\PostsFactory
     */
    protected $resPostsFactory;

    /**
     * DellPost constructor.
     * @param Context $context
     * @param PageFactory $resultPageFactory
     * @param \Magebay\Hello\Model\PostsFactory $postsFactory
     * @param \Magebay\Hello\Model\ResourceModel\PostsFactory $resPostsFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        \Magebay\Hello\Model\PostsFactory $postsFactory,
        \Magebay\Hello\Model\ResourceModel\PostsFactory $resPostsFactory
    )
    {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
        $this->postsFactory = $postsFactory;
        $this->resPostsFactory = $resPostsFactory;

    }

    /**
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
     */
    public function execute()
    {
        $postId = 3; // post Id
        $postModel = $this->postsFactory->create();
        try {
            $postModel->setId($postId);
            $this->resPostsFactory->create()->delete($postModel);
            echo "You have deleted item successfully! ";
        }
        catch (\Exception $exception)
        {
            echo $exception->getMessage();
        }
    }
}

After accessing yourdomain.com/hello/index/dellPost to see result

if you back to list posts and then you will see the post that you have deleted successfully.


Model is the most importance when building Magento 2 extension so it maybe complex for beginner but don’t worry about that . As you can see in this post and all posts in the tutorial , I introduce as simple as possible so You just focus to the tutorial and do step by step, you will understand and build a module by yourself. You can comment under this post if you have any question about How to use Model in Magento 2 extension.  I will introduce How to use Helper and Setting in Magento 2 extension in the next post.