Использовать EntityManager в файле Migrations
У меня есть этот код, но он не работает:
<?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");
}
}
У меня есть информация в мобильном телефоне в новом полетелефоне.
Спасибо
Ответы
Ответ 1
Это может быть более старое сообщение, но пока проблема решена и фактически является частью текущей документации.
См. 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
}
}
Ответ 2
Вы должны называть свои изменения в методе postUp()
- addSql()
- Заявления будут выполняться после завершения метода up()
, поэтому ваши новые строки (т.е. телефонфон) недоступны во время метода up()
!