Model from database tables with Doctrine ORM

Sometimes it is required to use some kind of reverse engineer with Doctrine ORM to extract models from an existing database, this time we have a MySQL database and we want to extract the models.

Before start, we need to install Composer and the Doctrine, easiest way to install this packages is the following:

1 – Create your project folder, i.e. “DoctrineSample”
2 – Go to your project folder and execute following command from console “php -r “readfile(‘’);” | php”, this will install composer inside your project folder
3 – Create a file to stablish project depedencies and name it “composer.json” with the following content:

4 – Then we must install it by using “php composer.phar install”, this will download the package inside “vendor” folder
5 – Now we are ready to start, and that means to follow Doctrine configuration manual, you can follow it here ( or keep reading this article for an quicker solution.

Next step: Project and Database setup

1 – For this sample I have created a simple database with just one table and no relationships, it’s up to you to add complexity as you need, take into account final notes in this article about limitations of Doctrine, database schema is the following:

2 – Create a file named “bootstrap.php” with the following content (take into account that database is named ‘test), fill it with your database credentials:

Now we are ready to get the models from the tables by using reverse engineer provided by Doctrine, i.e. if we want to get the models in YAML format we need an additional step, we should go back again to composer.json and add the following dependency “symfony/yaml”: “*”, then we need to update the dependencies with “php composer.phar update” command.

After that we are able to execute our reverse engineer command, create a folder under your project structure in which will be saved the YAML models, i.e. “src”, then, execute the command:

First create a file named “cli-config.php” with following content:

vendor\bin\doctrine orm:convert-mapping –from-database yaml src/

Once executed we can see tables mapping as YAML have been created inside “src” folder and content for this sample is:

Command for reverse engineer, from database to php models (xml, yaml, annotations):
vendor\bin\doctrine orm:convert-mapping –from-database annotation api/src/
vendor\bin\doctrine orm:convert-mapping –from-database xml api/src/
vendor\bin\doctrine orm:convert-mapping –from-database yaml api/src/

Note: This mapping could be affected by an Doctrine known issue, it’s not allowed to create a mapping with N:M relationships because doctrine does not support N:M relationships with PRIMARY KEYS as FOREIGN KEYS

Posted in Bases de datos, PHP Tagged with: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *