Generate Entity, xml, yml from existing database using doctrine2

by biplob


Posted on August 24, 2014 at 9:00 PM

Tags : : doctrine2


Sometimes we may need to generate Entity or xml, yml files from existing database which saves our time. I'm explaining it with few easy steps. This may also consider as getting started with doctrine2.

Sometimes we may need to generate Entity or xml, yml files from existing database which saves our time. I’m explaining it with few easy steps. This may also consider as getting started with doctrine2.

Step-1: If you’re on mac, open your terminal and go to your project root directory.

mkdir MyProject
cd MyProject

Step-2: Assuming you’ve composer installed. If not, check Composer documentation. Run the following commands.

composer require doctrine/orm

// If you want to generate yml files
composer require symfony/yaml

composer install

Step-3: Autoloading is taken care of by Composer. You just have to include the composer autoload file in your project. Once you have prepared the class loading, you acquire an EntityManager instance. Create the following file in your project root directory.

 'pdo_mysql',
    'user'     => 'root',
    'password' => 'root',
    'dbname'   => 'DB_NAME',
);
$entityManager = EntityManager::create($dbParams, $config);

For more details, check the [documentation](http://docs.doctrine-project.org/en/latest/tutorials/getting-started.html)

Step-4: Create the following to use doctrine console.



For more details check the documentation.

Step-5: Generate doctrine2 model from database with the following command. You can use ‘annotation’ or ‘yml’ instead of ‘xml’. And I’m using config/xml as output folder.

php vendor/bin/doctrine orm:convert-mapping --from-database xml /path/to/output/folder

Step-6 Generate entities from the xml files with the following command.

php vendor/bin/doctrine orm:generate:entities dest/path/ --no-backup

Source code of this project is available here.

Tips

You may get the following error while mapping from database.

[Doctrine\ORM\Mapping\MappingException]                                                                                                     
Table FileImageThumbnailPaths has no primary key. Doctrine does not support reverse engineering from tables that don't have a primary key. 

Do the following trick to skip this error. Navigate to your vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.phpfile. Add continue; on line 288. The code will look like as follows-

if ( ! $table->hasPrimaryKey()) {
    continue;
    throw new MappingException(
        "Table " . $table->getName() . " has no primary key. Doctrine does not ".
        "support reverse engineering from tables that don't have a primary key."
    );
}

 



Comments


You must be loged to add a comment !