在迁移文件中使用EntityManager

Zar*_*ele 21 migration symfony doctrine-orm

我有这个代码,但不起作用:

<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration,
    Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your need!
 */
class Version20131021150555 extends AbstractMigration
{

    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql", "Migration can only be executed safely on 'mysql'.");

        $this->addSql("ALTER TABLE person ADD tellphone LONGTEXT DEFAULT NULL");

        $em = $em = $this->getDoctrine()->getEntityManager();
        $persons = $em->getRepository('AutogestionBundle:Person')->fetchAll();

        foreach($persons as $person){
            $person->setTellPhone($person->getCellPhone());
            $em->persist($person);                                                                            
        }
        $em->flush(); 
    }

    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql", "Migration can only be executed safely on 'mysql'.");

        $this->addSql("ALTER TABLE person DROP tellphone");
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经在手机中添加了一个新的字段tellphone信息.

谢谢

小智 51

这可能是一个较旧的帖子,但同时问题已解决,实际上是当前文档的一部分.

请参阅http://symfony.com/doc/current/bundles/DoctrineMigrationsBundle/index.html#container-aware-migrations

// ...
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;

class Version20130326212938 extends AbstractMigration implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    public function up(Schema $schema)
    {
        // ... migration content
    }

    public function postUp(Schema $schema)
    {
        $em = $this->container->get('doctrine.orm.entity_manager');
        // ... update the entities
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 12

我确实意识到这有点老了,但要从我的错误中吸取教训,并且:

甚至不要考虑在迁移中使用实体管理器

特别是在您想要使用它的方式 - 获取实体存储库。

这是为什么。

想象一下你有一个DogEntitywith 字段的情况$name。您现在基于该实体生成一个迁移文件(可以说它的 Version1)。到现在为止还挺好。

接下来,您要使用实体管理器来获取该存储库DogEntity,更新记录,对该实体执行任何您需要执行的操作。这有效并且没问题(假设此迁移文件的名称为 Version2)。

现在,您将一个$color字段添加到您的DogEntity,再次生成迁移(它是一个名为 Version3 的文件)。而且没关系...

...直到您尝试从一开始就运行所有迁移。在那一刻,错误将在 Version2 文件的迁移过程中抛出。为什么?因为实体管理器color在数据库中查找该字段。但该字段是稍后在 Version3 文件中创建的。

TLDR:实体管理器会查找您当前在实体中拥有的列,这些列可能会在从一开始运行迁移时导致问题。


小智 6

您必须在postUp()方法中调用您的修改- addSql()up()方法完成后将执行语句,因此在up()方法期间您的新行(即tellphone)不可用!