[ACCEPTED]-How do I write a Doctrine migration which can redistribute data into new tables-doctrine-migrations
Accepted answer
OK, I seem to have found it, from a number 10 of sources (including this) and trial and error.
Cerad's 9 comments were a little help, but mainly 8 I'm doing it by using the DBAL layer to 7 read in the data (which I can get at by 6 $this->connection
), and the ORM to save the new data (which 5 requires the EntityManager, so I did have 4 to use the trick with the container).
I put 3 all the code in postUp()
, including the generated 2 code to drop columns from tables.
Sample 1 bits of my code:
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use PG\InventoryBundle\Entity\Item;
use PG\InventoryBundle\Entity\Address;
.
.
.
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20140519211228 extends AbstractMigration implements ContainerAwareInterface
{
private $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function up(Schema $schema)
{
.
.
.
}
}
public function postUp(Schema $schema)
{
$em = $this->container->get('doctrine.orm.entity_manager');
// ... update the entities
$query = "SELECT * FROM item";
$stmt = $this->connection->prepare($query);
$stmt->execute();
// We can't use Doctrine's ORM to fetch the item, because it has a load of extra fields
// that aren't in the entity definition.
while ($row = $stmt->fetch()) {
// But we will also get the entity, so that we can put addresses in it.
$id = $row['id'];
// And create new objects
$stock = new Stock();
.
.
.
$stock->setAssetNo($row['asset_no']);
$stock->setItemId($row['id']);
$em->persist($stock);
$em->flush();
}
// Now we can drop fields we don't need.
$this->connection->executeQuery("ALTER TABLE item DROP container_id");
$this->connection->executeQuery("ALTER TABLE item DROP location_id");
.
.
.
}
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.