首页 > 解决方案 > Doctrine 对 ENUM 类型的实体做出了不正确的差异

问题描述

我通过cookbook为实体CommandENUM的属性类型做了一个特殊类型。


该属性如下所示:

    /**
     * @var CommandType
     *
     * @ORM\Column(type="command_type")
     */
    protected $type;


这个片段描述了新的学说类型:

final class CommandTypeType extends EnumerableType
{
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return 'VARCHAR(30)';
    }

    public function getName(): string
    {
        return 'command_type';
    }

    protected function getClassName(): string
    {
        return CommandType::class;
    }
}


/bin/console doctrine:migrations:diff在第一次为实体运行命令后,我得到了迁移,它看起来是正确的

final class Version2020 072720500 extends AbstractMigration
{
    public function up(Schema $schema) : void
    {
        $this->addSql("CREATE TABLE commands (
                id INT AUTO_INCREMENT NOT NULL,
                name VARCHAR(30) DEFAULT NULL,
                command VARCHAR(100) DEFAULT NULL,
                type varchar(30) NOT NULL,
                PRIMARY KEY(id)
        ) DEFAULT CHARACTER SET UTF8 COLLATE `UTF8_unicode_ci` ENGINE = InnoDB");
    }

    public function down(Schema $schema) : void
    {
        $this->addSql('DROP TABLE commands');
    }
}


下一步是运行命令/bin/console doctrine:migrations:migrate,它工作正常,表已创建。

然后我/bin/console doctrine:migrations:diff再次运行命令并获得新的迁移

final class Version20200727205035 extends AbstractMigration
{
    public function up(Schema $schema) : void
    {
        $this->addSql('ALTER TABLE commands CHANGE type type VARCHAR(30) NOT NULL');
    }

    public function down(Schema $schema) : void
    {
        $this->addSql('ALTER TABLE commands CHANGE type type VARCHAR(30) CHARACTER SET utf8 NOT NULL COLLATE `utf8_unicode_ci`');
    }
}


我不知道为什么第二个差异会产生这种奇怪的迁移。 我做错了什么?

标签: symfonydoctrine-ormdoctrine

解决方案


Doctrine 需要在列中添加注释以检测自定义类型已应用于列。

检查requiresSQLCommentHint方法是否已实现并返回 true 或将其添加到您的自定义类型。

final class CommandTypeType extends EnumerableType
{
    ...

    public function requiresSQLCommentHint(AbstractPlatform $platform): bool
    {
        return true;
    }
}

您应该会在下次迁移时看到将添加到您的列中的评论,仅此而已。


推荐阅读