How to Generate Entities from an Existing Database

How to Generate Entities from an Existing Database

When starting work on a brand new project that uses a database, two different situations comes naturally. In most cases, the database model is designed and built from scratch. Sometimes, however, you’ll start with an existing and probably unchangeable database model. Fortunately, Doctrine comes with a bunch of tools to help generate model classes from your existing database.

Note

As the Doctrine tools documentation says, reverse engineering is a one-time process to get started on a project. Doctrine is able to convert approximately 70-80% of the necessary mapping information based on fields, indexes and foreign key constraints. Doctrine can’t discover inverse associations, inheritance types, entities with foreign keys as primary keys or semantical operations on associations such as cascade or lifecycle events. Some additional work on the generated entities will be necessary afterwards to design each to fit your domain model specificities.

This tutorial assumes you’re using a simple blog application with the following two tables: blog_post and blog_comment. A comment record is linked to a post record thanks to a foreign key constraint.

  1. CREATE TABLE `blog_post` (
  2. `id` bigint(20) NOT NULL AUTO_INCREMENT,
  3. `title` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  4. `content` longtext COLLATE utf8_unicode_ci NOT NULL,
  5. `created_at` datetime NOT NULL,
  6. PRIMARY KEY (`id`)
  7. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
  8. CREATE TABLE `blog_comment` (
  9. `id` bigint(20) NOT NULL AUTO_INCREMENT,
  10. `post_id` bigint(20) NOT NULL,
  11. `author` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  12. `content` longtext COLLATE utf8_unicode_ci NOT NULL,
  13. `created_at` datetime NOT NULL,
  14. PRIMARY KEY (`id`),
  15. KEY `blog_comment_post_id_idx` (`post_id`),
  16. CONSTRAINT `blog_post_id` FOREIGN KEY (`post_id`) REFERENCES `blog_post` (`id`) ON DELETE CASCADE
  17. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Before diving into the recipe, be sure your database connection parameters are correctly setup in the .env file (or .env.local override file).

The first step towards building entity classes from an existing database is to ask Doctrine to introspect the database and generate the corresponding metadata files. Metadata files describe the entity class to generate based on table fields.

  1. $ php bin/console doctrine:mapping:import "App\Entity" annotation --path=src/Entity

This command line tool asks Doctrine to introspect the database and generate new PHP classes with annotation metadata into src/Entity. This generates two files: BlogPost.php and BlogComment.php.

Tip

It’s also possible to generate the metadata files into XML or eventually into YAML:

  1. $ php bin/console doctrine:mapping:import "App\Entity" xml --path=config/doctrine

In this case, make sure to adapt your mapping configuration accordingly:

  1. # config/packages/doctrine.yaml
  2. doctrine:
  3. # ...
  4. orm:
  5. # ...
  6. mappings:
  7. App:
  8. is_bundle: false
  9. type: xml # "yml" is marked as deprecated for doctrine v2.6+ and will be removed in v3
  10. dir: '%kernel.project_dir%/config/doctrine'
  11. prefix: 'App\Entity'
  12. alias: App

Generating the Getters & Setters or PHP Classes

The generated PHP classes now have properties and annotation metadata, but they do not have any getter or setter methods. If you generated XML or YAML metadata, you don’t even have the PHP classes!

To generate the missing getter/setter methods (or to create the classes if necessary), run:

  1. // generates getter/setter methods for all Entities
  2. $ php bin/console make:entity --regenerate App
  3. // generates getter/setter methods for one specific Entity
  4. $ php bin/console make:entity --regenerate App\\Entity\\Country

Note

If you want to have a OneToMany relationship, you will need to add it manually into the entity (e.g. add a comments property to BlogPost) or to the generated XML or YAML files. Add a section on the specific entities for one-to-many defining the inversedBy and the mappedBy pieces.

The generated entities are now ready to be used. Have fun!

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.