Home » Php » php – Symfony2 doctrine update schema from specific entity

php – Symfony2 doctrine update schema from specific entity

Posted by: admin July 12, 2020 Leave a comment


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?

How to&Answers:

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.


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.