magento2 创建数据表及添加索引

  最近在用 magento2 做项目时,需要根据业务需求增加新的数据表,且增加相应的索引,现在如下记录:
  在模块下创建 Setup 目录,增加 InstallSchema.php 文件,代码如下:
<?php

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

/**
 * @codeCoverageIgnore
 */
class InstallSchema implements InstallSchemaInterface
{
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();

        /**
         * create table
         */
        $this->createGuestWishlistTable($installer);

        $installer->endSetup();
    }

    /**
     * create table wishlist_guest
     * @param $installer
     */
    private function createGuestWishlistTable($installer)
    {
        $tableName = $installer->getTable('wishlist_guest');
        $wishlistGuest = $installer->getConnection()->newTable($tableName)
            ->addColumn(
                'guest_id',
                \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                10,
                [
                    'primary' => true,
                    'identity' => true,
                    'unsigned' => true,
                    'nullable' => false
                ],
                'Guest Wishlist Id'
            )->addColumn(
                'pc_guest_cookie',
                \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                50,
                ['nullable' => false, 'default' => ''],
                'Pc Guest Cookie'
            )->addColumn(
                'applet_customer_id',
                \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                10,
                ['nullable' => false, 'default' => ''],
                'Applet Customer Id'
            )->addColumn(
                'updated_at',
                \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
                null,
                [],
                'Update Time'
            )->addIndex(
                $installer->getIdxName('wishlist_guest', ['pc_guest_cookie']),
                ['pc_guest_cookie'],
                \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
            )->addIndex(
                $installer->getIdxName('wishlist_guest', ['applet_customer_id']),
                ['applet_customer_id']
            )->setComment('guest wishlist');
        $installer->getConnection()->createTable($wishlistGuest);
    }

}

备注:创建唯一键索引的时候需要需要增加 type 类型,即
magento2 创建数据表及添加索引

本作品采用《CC 协议》,转载必须注明作者和本文链接
May
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!