生成数据库 MyISAM Doctrine 2

Generate Database MyISAM Doctrine 2

我正在使用 Doctrine 基于我的实体生成和更新我的数据库。此外,我在我的表上使用了 MyISAM 引擎。为此,我添加了如下注释:

/** (...) @ORM\Table(name="user",options={"engine":"MyISAM", "charset"="utf8"}) */

这些表通常是作为 MyISAM 生成的,但是当我现在尝试更新它们时,学说正在尝试生成 FK。然后我得到:

 General error: 1215 Cannot add foreign key constraint

我知道 MyISAM 不支持 FK,有没有办法告诉 doctrine 跳过 FK 的创建?

I am using both orm:schema-tools:update (in DEV) and migrations (in PROD). Also I am using zf2.

MyISAM 存储引擎不支持行级锁定、外键,甚至不支持事务。查看 this question 以获得更详细的答案。

如果您没有任何特定且正当的理由使用 MyISAM,我强烈建议改用 InnoDB。

您可能还想阅读这篇文章 comparison between InnoDB and MyISAM

基于this thread我想出了一个解决方案

我给 EM 添加了一个事件监听器。

$em->getEventManager()->addEventSubscriber(new DropForeignKeysListener());

此事件从注释生成的模式中删除所有 FK,如:

use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Tools\ToolEvents;
use Doctrine\ORM\Tools\Event\GenerateSchemaEventArgs;

class DropForeignKeysListener implements EventSubscriber
{
    public function postGenerateSchema(GenerateSchemaEventArgs $args) {
        $schema = $args->getSchema();

        $table_names = $schema->getTableNames();
        foreach ($table_names as $table_name) {
            $table = $schema->getTable($table_name);
            $fks = $table->getForeignKeys();

            foreach ($fks as $fk => $obj) {
                $table->removeForeignKey($fk);
            }
        }
    }

    public function getSubscribedEvents() {
        return array(ToolEvents::postGenerateSchema);
    }

}