Magento2 creating data tables and adding indexes

Time:2021-9-25
Recently, when magento2 was used as a project, new data tables and corresponding indexes need to be added according to business requirements. Now the following records are recorded:
<?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);
    }

}

Note: when creating a unique key index, you need to add a type, that is

Magento2 creating data tables and adding indexes

This work adoptsCC agreement, reprint must indicate the author and the link to this article

May