Symfony2 Generate Entities Starting from a Database

As I figured it out, until now, Symfony2 hasn’t got a common schema.yml for all entities (an entity is a class/object that maps the correspondent table) as was in Symfony 1.4, but the database configurations are made separate for every entity. In these conditions creating a database starting from the existing entities is a much more laborious task than it was in Symfony 1.4, but not impossible.

There is, although, another solution to this problem, building the entities starting from an existing database. There is a good tutorial in Symfony2 cookbook, but I will also list here the commands needed to complete this task. All of these commands assume that I configured the parameter.ini correctly, so Symfony knows which is the database to use, and also that the bundle Main/MyBundle is initialized, in order to store the entities that will be created.

1. First Symfony needs to generate the metadata corresponding to the tables through the following command. This will create YAML files but it can also create XML files.

     php app/console doctrine:mapping:convert yml ./src/Main/MyBundle /Resources/config/doctrine/metadata/orm --from-database --force

2. Now Symfony can import the configurations from the metadata files

     php app/console doctrine:mapping:import MainMyBundle yml

3. The entities can be generated based on the configuration files

     php app/console doctrine:generate:entities MainMyBundle

That’s all!

But one needs to pay attention to the way he builds his database from the beginning.  For example the relations too must be specified when building the database otherwise Doctrine will not be able to detect them. In phpMyAdmin this is done in the following way:

  • go to the structure of the table that will contain the foreign key
  • create an index on the field that you want it to be a foreign key
  • go back to the structure of the table and click Relation View
  • on the field that we want to make a foreign key specify to which other key it is related

For example if you want to have two tables book and author, than the primary key will be in author table, since it is unique, but one author can write one or many books, and the foreign key will be the author_id field in book table.

2 thoughts on “Symfony2 Generate Entities Starting from a Database

  1. interesting but got a bit lost, i wish you could have pasted screenshots of the stuff phpmyadmin and also draw some tables to make it plain. Also indicating the product of each command. 1 or several images can save you a ton of words and words will add to it. Thanks, hope to see more posts or improved ones.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>