我刚从 Magento 1.7 升级。我成功地创建了模块、控制器、助手等。
今天我尝试用自定义表格创建一个模型。我希望自动创建表。我做了以下步骤:
我创建了一个具有以下目录结构的模块:
<Ashutosh>
<Pandey>
<etc>
module.xml
<Model>
<Setup>
InstallSchema.php
以下是每个文件的内容:
安装Schema.php
<?php
namespace Ashutosh\Pandey\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)
{
$installer = $setup;
$installer->startSetup();
// Get table
$tableName = $installer->getTable('ashutosh_friends');
// Check if the table already exists
if ($installer->getConnection()->isTableExists($tableName) != true) {
// Create tutorial_simplenews table
$table = $installer->getConnection()
->newTable($tableName)
->addColumn(
'id',
Table::TYPE_INTEGER,
null,
[
'identity' => true,
'unsigned' => true,
'nullable' => false,
'primary' => true
],
'ID'
)
->addColumn(
'name',
Table::TYPE_TEXT,
null,
['nullable' => false, 'default' => ''],
'Title'
)
->addColumn(
'friend_type',
Table::TYPE_TEXT,
null,
['nullable' => false, 'default' => ''],
'Summary'
)
->addColumn(
'created_at',
Table::TYPE_DATETIME,
null,
['nullable' => false],
'Created At'
)
->addColumn(
'status',
Table::TYPE_SMALLINT,
null,
['nullable' => false, 'default' => '0'],
'Status'
)
->setComment('Ashutosh Friends Table')
->setOption('type', 'InnoDB')
->setOption('charset', 'utf8');
$installer->getConnection()->createTable($table);
}
$installer->endSetup();
}
}
模块.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Ashutosh_Pandey" setup_version="1.0.0" active="true"/>
</config>
然后在我的 magento2 目录的命令提示符下,我执行了命令:
php bin/magento setup:upgrade
该命令成功运行,但未创建表。然后我还执行了命令:
php bin/magento setup:db-schema:upgrade
但仍然没有任何反应。
注意:如果我在数据库中手动创建表,我可以成功读取表。