最近在用 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 型別,即
本作品採用《CC 協議》,轉載必須註明作者和本文連結