Щоб додати нову таблицю до бази даних Magento 2, потрібно створити файл у папка модулів :
app/code// /Setup/InstallSchema.php
та додати до нього наступний код:
namespace VendorName\ModuleName\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Adapter\AdapterInterface;
class InstallSchema implements InstallSchemaInterface
{
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$installer = $setup;
$installer->startSetup();
//new table script will be there
$installer->endSetup();
}
}
InstallSchema.php — це файл, який відповідає за зміну структури бази даних під час встановлення модулів. Під час виконання команди CLI php bin/magento setup:upgrade Magento 2 перевіряє, чи з'явився новий модуль у системі та чи містить він файл InstallSchema.php. Якщо так, цей файл викликає свій метод встановлення ($ setup, context).
Примітка: InstallSchema.php не працюватиме, якщо модуль був встановлений раніше.
Дані про версії встановлених модулів зберігаються в таблиці " setup_module ", що знаходиться в базі даних Magento 2. Якщо під час тестової інсталяції модуля в базі даних була створена неочікувана структура, видаліть її разом із записом вашого модуля з таблиці " setup_module ".
Виправте код та знову запустіть команду php bin/magento setup:upgrade .
У прикладі ми створимо таблицю для часто задаваних питань (FAQ) та таблицю для зберігання залежностей FAQ — Store View, іншими словами, якими мовами буде доступна стаття FAQ.
Замініть коментар "// там буде новий скрипт таблиці" у файлі InstallSchema.php наступним кодом:
/**
* Create table 'magefan_faq'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('magefan_faq')
)->addColumn(
'faq_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'nullable' => false, 'primary' => true],
'FAQ ID'
)->addColumn(
'title',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
['nullable' => true],
'FAQ Title'
)->addColumn(
'meta_keywords',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
['nullable' => true],
'FAQ Meta Keywords'
)->addColumn(
'meta_description',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'64k',
['nullable' => true],
'FAQ Meta Description'
)->addColumn(
'identifier',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
100,
['nullable' => true, 'default' => null],
'FAQ String Identifier'
)->addColumn(
'content_heading',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
['nullable' => true],
'FAQ Content Heading'
)->addColumn(
'content',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'2M',
[],
'FAQ Content'
)->addColumn(
'creation_time',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
[],
'FAQ Creation Time'
)->addColumn(
'update_time',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
[],
'FAQ Modification Time'
)->addColumn(
'is_active',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['nullable' => false, 'default' => '1'],
'Is FAQ Active'
)->addIndex(
$installer->getIdxName('magefan_faq', ['identifier']),
['identifier']
)->setComment(
'Magefan FAQ Table'
);
$installer->getConnection()->createTable($table);
/**
* Create table 'magefan_faq_store'
*/
$table = $installer->getConnection()->newTable(
$installer->getTable('magefan_faq_store')
)->addColumn(
'faq_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['nullable' => false, 'primary' => true],
'FAQ ID'
)->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
['unsigned' => true, 'nullable' => false, 'primary' => true],
'Store ID'
)->addIndex(
$installer->getIdxName('magefan_faq_store', ['store_id']),
['store_id']
)->addForeignKey(
$installer->getFkName('magefan_faq_store', 'faq_id', 'magefan_faq', 'faq_id'),
'faq_id',
$installer->getTable('magefan_faq'),
'faq_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->addForeignKey(
$installer->getFkName('magefan_faq_store', 'store_id', 'store', 'store_id'),
'store_id',
$installer->getTable('store'),
'store_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)->setComment(
'Magefan FAQ To Store Linkage Table'
);
$installer->getConnection()->createTable($table);
Нижче наведено специфікацію методів.
Метод addColumn :
/** * Adds a column to the table. * * $options contains additional options for the column. Allowed parameters: * - 'unsigned', is used only for numeric types. By default, gets the FALSE value; * - 'precision', is used only for numeric types. By default, gets a value from the $ size parameter, otherwise 0; * - 'scale', is used only for numeric types. By default, gets a value from the $ size parameter, otherwise equal to 10; * - 'default', no default value; * - 'nullable', default value: TRUE; * - 'primary', adds a column to the primary index. By default, the column is not added to the primary index; * - 'primary_position', the column from the primary index is used. The default value: number of primary columns + 1; * - 'identity' or 'auto_increment'. no default value; * * @param string $name - column name; * @param string $type - column data type; * @param string|integer|array $size - length (size) of the column; * @param array $options array with additional options; * @param string $comment - comment to the column; * @return $this */ public function addColumn($name, $type, $size = null, $options = [], $comment = null)
Метод setComment :
/**
* Sets a comment to the table.
*
* @param string $comment - text of the comment;
* @return $this
*/
public function setComment($comment)
Метод addIndex :
/**
* Adds an index to the table.
*
* @param string $indexName - index name;
* @param array or string $fields - an array of column names or a column name;
* @param array $options - an array of additional options;
* @return $this
*/
public function addIndex($indexName, $fields, $options = [])
Метод addForeignKey :
/** * Adds foreign key to the table. * * @param string $fkName - the name of the foreign key; * @param string $column - the name of the column key for the foreign key; * @param string $refTable - the name of the foreign table; * @param string $refColumn - name of foreign columns; * @param string $onDelete - event to delete a line; * @return $this */ public function addForeignKey($fkName, $column, $refTable, $refColumn, $onDelete = null)
Усі ці методи оголошені у файлі vendor/magento/framework/DB/Ddl/Table.php.
Збережіть файл InstallSchema.php . Якщо ваш модуль знаходиться в таблиці 'setup_module', видаліть його.
Запустіть процес встановлення модуля, виконайте команду CLI:
php bin/magento setup:upgrade
Перевірте структуру бази даних, наприклад, за допомогою phpMyAdmin . Ви побачите нові таблиці.
![]()
База даних Magento 2 містить близько 200 таблиць, якщо ви не можете знайти свою, перейдіть на наступну сторінку списку.
Ви можете переглянути змінені файли модуля Magefan_Faq на GitHub.