Hướng dẫn dùng Model trong Magento 2

Tiếp tục series hướng dẫn lập trình module, trong bài viết này mình sẽ hướng dẫn các bạn cách sử dụng Model trong Magento 2 để truy xuất dữ liệu từ database.

Bước 1: Thêm dữ liệu vào database

Để có thể truy xuất dữ liệu từ database chúng ta cần thêm dữ liệu vào database, trong đường dẫn app\code\Magetop\Helloworld\Setup\ tạo file InstallData.php với đoạn code sau:

<?php
namespace Magetop\Helloworld\Setup;

use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;


class InstallData implements InstallDataInterface
{
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        $tableName = $setup->getTable('magetop_hello');
        if($setup->getConnection()->isTableExists($tableName) == true){
            $data = [
                [
                    'title' => 'Blog 1',
                    'summary' => 'summary blog 1',
                    'description' => 'description blog 1',
                    'status' => 1,
                    'create_at' => date('Y-m-d H:i:s'),
                ],
                [
                    'title' => 'Blog 2',
                    'summary' => 'summary blog 2',
                    'description' => 'description blog 2',
                    'status' => 1,
                    'create_at' => date('Y-m-d H:i:s'),
                ],
                [
                    'title' => 'Blog 3',
                    'summary' => 'summary blog 3',
                    'description' => 'description blog 3',
                    'status' => 1,
                    'create_at' => date('Y-m-d H:i:s'),
                ],
            ];
            foreach ($data as $item){
                $setup->getConnection()->insert($tableName, $item);
            }
        }
        $setup->endSetup();
    }
}

Các bạn có thể tùy chỉnh dữ liệu tùy theo ý của mình.

Tạo xong các bạn tăng setup_version trong file module.xml lên rồi chạy lệnh php bin/magento setup:upgrade.

Bây giờ chúng ta vào bảng magetop_hello kiểm tra.

dữ liệu bảng magetop_hello

Trường hợp nếu tăng version module lên rồi mà vẫn không thấy data thì bạn hãy thử gỡ module đi cài lại.

Bước 2: Tạo Model

Các bạn tạo thư mục Model theo đường dẫn app\code\Magetop\Helloworld\Model. Tạo file Posts.php trong thư mục Model với đoạn code:

<?php
namespace Magetop\Helloworld\Model;

use Magento\Framework\Model\AbstractModel;

class Posts extends AbstractModel{
    protected function _construct()
    {
        $this->_init('Magetop\Helloworld\Model\ResourceModel\Posts');
    }
}

Tiếp theo tạo file Posts.php theo đường dẫn app\code\Magetop\Helloworld\Model\ResourceModel\ kèm đoạn code:

<?php
namespace Magetop\Helloworld\Model\ResourceModel;

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

class Posts extends AbstractDb
{
    protected function _construct()
    {
        // magetop_hello là tên bảng , id là khóa chính primary của bảng
        $this->_init('magetop_hello', 'id');
    }
}

Theo đường dẫn app\code\Magetop\Helloworld\Model\ResourceModel\Posts\ tạo file Collection.php với đoạn code:

<?php
namespace Magetop\Helloworld\Model\ResourceModel\Posts;

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

class Collection extends AbstractCollection
{
    protected function _construct()
    {
        $this->_init(
            'Magetop\Helloworld\Model\Posts',
            'Magetop\Helloworld\Model\ResourceModel\Posts'
        );
    }
}

Bước 3: Lấy dữ liệu từ database

Tạo file Data.php theo đường đẫn app\code\Magetop\Helloworld\Controller\Get\ với đoạn code:

<?php
namespace Magetop\Helloworld\Controller\Get;

use Magento\Framework\App\Action\Action;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Context;
use Magetop\Helloworld\Model\ResourceModel\Posts\CollectionFactory;

class Data extends Action
{
    protected $PageFactory;
    protected $PostsFactory;

    public function __construct(Context $context, PageFactory $pageFactory, CollectionFactory $postsFactory)
    {
        parent::__construct($context);
        $this->PageFactory = $pageFactory;
        $this->PostsFactory = $postsFactory;
    }

    public function execute()
    {
        echo "Lấy dữ liệu từ bảng magetop_hello";
        $this->PostsFactory->create();
        $collection = $this->PostsFactory->create()
            ->addFieldToSelect(array('title','summary','description','status','create_at'))
            ->addFieldToFilter('status',1)
            ->setPageSize(10);
        echo '<pre>';
        print_r($collection->getData());
        echo '<pre>';
    }
}

Xong các bạn chạy lệnh:

  • php bin/magento setup:upgrade
  • php bin/magento setup:static-content:deploy -f
  • php bin/magento cache:clean

Giờ truy cập vào địa chỉ <domain-cua-ban>/hello/get/data để kiểm tra.

show dữ liệu bảng magetop_hello

Dữ liệu đúng với trong bảng.

Vậy là mình đã hướng dẫn xong cách sử dụng Model trong Magento 2.

Để dễ hiểu hơn các bạn nên đọc các bài viết hướng dẫn trước của mình: Hướng dẫn lập trình module Magento 2 (phần 2).

Ở bài hướng dẫn tiếp theo mình sẽ hướng dẫn các bạn cách tạo view trong Magento 2.

Cảm ơn các bạn đã đọc bài viết.

4.8 5 votes
Article Rating

Callula Huy

Callula is the Marketing Executive at Magetop. With more than 5 years of copywriting under her belt, Callula is into creating valuable content that is straight to the point. Life student. Workaholic. Foreign languages and traveling aficionado.

Leave a Reply or put your Question here

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x