Symfony2 doctrine update schema from specific entity

15,505

Solution 1

According to the command documentation, there is no such option. If this is something you have to do only once, I'd suggest to use the --dump-sql option to get the required SQL instructions, and manually run the ones you need.

P.S. I fail to understand what's the reason to only update the schema for an entity, and leave all the rest of entities not sync'd with the database. That sounds like a recipe for getting db errors.

Solution 2

You can manually use the Doctrine SchemaTool class to generate an SQL diff based only on a single entity. You’ll need access to Doctrine’s EntityManager – the example below assumes access to Symfony’s container.

use Doctrine\ORM\Tools\SchemaTool;

$em = $this->container->get('doctrine')->getManager();
$schemaTool = new SchemaTool($em);
$metadata = $em->getClassMetadata(YourEntity::class);
$sqlDiff = $schemaTool->getUpdateSchemaSql([$metadata], true);

The variable $sqlDiff will now contain an array of SQL statements that are needed to bring the database schema up to date with your entity mapping.

The second argument passed to SchemaTool::getUpdateSchemaSql() is important – without it, the default behaviour would be to generate DROP TABLE statements for every other table that appears in your database.

Share:
15,505
Wizard
Author by

Wizard

Updated on June 11, 2022

Comments

  • Wizard
    Wizard almost 2 years

    If I run

    php app/console doctrine:schema:update --force
    

    It will update my database from all entities.

    I need to update database only for the User entity, what is the solution?

    One solution is to define a custom entity manager and then pass that entity manager to

    php app/console doctrine:schema:update --force --em="custom"
    

    But maybe it exists something faster without defining a custom entity manager?