2013-10-21 4 views
15

ich diesen Code haben, funktioniert aber nicht:Verwenden EntityManager in Migrations-Datei

<?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"); 
    } 
} 

ich Informationen in einem neuen Feld tellphone in Handy hinzufügen müssen.

Dank

+0

Was meinst du mit 'nicht funktioniert'. Wie heißen diese Methoden? Was ist das erwartete und aktuelle Ergebnis? – ferdynator

+0

Diese Zeile erhält Fehler $ em = $ em = $ this-> getDoctrine() -> getEntityManager(); Ich brauche EntityManager in dieser Datei. Danke – Zarpele

+0

Es funktioniert nicht, weil Sie $ this-> getDoctrine(), AbstractMigration Klasse hat diese Methode nicht aufrufen. – zuzuleinen

Antwort

36

Dies könnte eine ältere Post sein, aber inzwischen ist das Problem gelöst und tatsächlich Teil der aktuellen Dokumentation.

Siehe 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 
    } 
} 
5

Sie müssen Ihre Änderungen in der postUp() Methode aufrufen - die addSql() - Anweisungen ausgeführt wird nach up() Verfahren abgeschlossen ist, so dass Ihre neue Zeilen (das heißt tellphone) sind während der up() Methode nicht zur Verfügung!

Verwandte Themen