Hướng dẫn tạo table database trong Magento 2

Ở bài trước mình đã hướng dẫn các bạn cách để tạo ra 1 module Magento 2. Trong bài viết này mình sẽ hướng dẫn các bạn cách tạo bảng(table) database trong Magento 2.

Bước 1: Tạo Module.

Đầu tiên các bạn cần tạo 1 module bằng cách tạo file module.xml và registration.php, mình đã có hướng dẫn ở bài viết trước các bạn có thể tham khảo: Hướng dẫn tạo module đơn giản trong Magento 2

Bước 2: Tạo file InstallSchema.php.

Các bạn tạo InstallSchema.php theo đường dẫn app\code\Magetop\Helloworld\Setup với đoạn code sau:

<?php

namespace Magetop\Helloworld\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;

class InstallSchema implements InstallSchemaInterface
{
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        $tableName = $setup->getTable('magetop_hello');
        // Kiểm tra xem tên bảng đã tồn tại hay chưa, nếu chưa thì tạo bảng
        if ($setup->getConnection()->isTableExists($tableName) != true) {
            $table = $setup->getConnection()->newTable($tableName)
                ->addColumn(
                    'id',
                    Table::TYPE_INTEGER,
                    null,
                    [
                        'identity' => true,
                        'unsigned' => true,
                        'nullable' => false,
                        'primary' => true
                    ],
                    'ID'
                )
                ->addColumn(
                    'title',
                    Table::TYPE_TEXT,
                    null,
                    ['nullable' => false, 'default' => ''],
                    'Title'
                )
                ->addColumn(
                    'summary',
                    Table::TYPE_TEXT,
                    null,
                    ['nullable' => false, 'default' => ''],
                    'Summary'
                )
                ->addColumn(
                    'description',
                    Table::TYPE_TEXT,
                    null,
                    ['nullable' => false, 'default' => ''],
                    'Description'
                )
                ->addColumn(
                  'status',
                  Table::TYPE_SMALLINT,
                  null,
                  [
                      'nullable' => false, 'default' => '0'
                  ],
                  'Status'
              )
              ->addColumn(
                  'create_at',
                  Table::TYPE_DATETIME,
                  null,
                  [
                      'nullable' => false
                  ],
                  'Create_at'
              )
                ->setComment('Magetop Hello')
                ->setOption('type', 'InnoDB')
                ->setOption('charset', 'utf8');
            $setup->getConnection()->createTable($table);
        }

        $setup->endSetup();
    }
}

Các bạn có thể chỉnh sửa và tạo bảng theo ý của mình.Khi tạo InstallSchema.php xong nếu bạn chưa kích hoạt module thì chỉ cần kích hoạt là sẽ tạo ra bảng database vì Magento sẽ tự động chạy file này khi cài đặt lần đầu.

Còn nếu bạn đã cài đặt module trước rồi thì bạn cần tăng setup_version trong file module.xml lên và tạo file UpgradeSchema.php.

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * module
 *
 * @copyright Copyright © 2020 MAGETOP. All rights reserved.
 * @author    [email protected]
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Magetop_Helloworld" setup_version="1.0.1">
    </module>
</config>

Nếu các bạn theo dõi bài trước của mình rồi thì sẽ biết mình đã tăng từ setup_version=”1.0.0″ lên thành setup_version=”1.0.1″.

Sau khi tăng version xong các bạn tạo file UpgradeSchema.php. với file này các bạn cũng có thể tạo thêm cột vào bảng của mình. đoạn code như sau:

<?php
namespace Magetop\Helloworld\Setup;

use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;


class UpgradeSchema implements UpgradeSchemaInterface
{
    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        $tableName = $setup->getTable('magetop_hello');
        if (version_compare($context->getVersion(), '1.0.1', '<')) {
             if ($setup->getConnection()->isTableExists($tableName) != true){
                 $table = $setup->getConnection()->newTable($tableName)
                     ->addColumn(
                         'id',
                         Table::TYPE_INTEGER,
                         null,
                         [
                             'identity' => true,
                             'unsigned' => true,
                             'nullable' => false,
                             'primary' => true
                         ],
                         'ID'
                     )
                     ->addColumn(
                         'title',
                         Table::TYPE_TEXT,
                         null,
                         ['nullable' => false, 'default' => ''],
                         'Title'
                     )
                     ->addColumn(
                         'summary',
                         Table::TYPE_TEXT,
                         null,
                         ['nullable' => false, 'default' => ''],
                         'Summary'
                     )
                     ->addColumn(
                         'description',
                         Table::TYPE_TEXT,
                         null,
                         ['nullable' => false, 'default' => ''],
                         'Description'
                     )
                     ->addColumn(
                         'status',
                         Table::TYPE_SMALLINT,
                         null,
                         [
                             'nullable' => false, 'default' => '0'
                         ],
                         'Status'
                     )
                     ->addColumn(
                         'create_at',
                         Table::TYPE_DATETIME,
                         null,
                         [
                             'nullable' => false
                         ],
                         'Create_at'
                     )
                     ->setComment('Magetop Hello')
                     ->setOption('type', 'InnoDB')
                     ->setOption('charset', 'utf8');
                 $setup->getConnection()->createTable($table);
             }
        }
        // Thêm cột vào bảng
        if(version_compare($context->getVersion(),'1.0.1','<')){
            if ($setup->getConnection()->isTableExists($tableName) == true){
                $column = [
                    'image' => [
                        'type' => Table::TYPE_TEXT,
                        ['nullable' => true, 'default' => ''],
                        'comment' => 'Image',
                    ],
                ];
                foreach ($column as $name => $definition){
                    $setup->getConnection()->addColumn($tableName, $name, $definition);
                }
            }
        }

        $setup->endSetup();
    }
}

Bước 3: Chạy lệnh.

Hoàn thành b1 b2 xong các bạn chạy lệnh: php bin/magento setup:upgrade.

Sau đó các bạn vào phpmyadmin kiểm tra.

phpmyadmin
phpmyadmin

Vậy là mình đã hướng xong cách tạo table database trong Magento 2

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

Bài viết tiếp theo mình sẽ hướng dẫn các bạn cách sử dụng Model trong Magento 2.

4.5 4 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