Databases and the Doctrine ORM

Databases and the Doctrine ORM

Screencast

Do you prefer video tutorials? Check out the Doctrine screencast series.

Symfony provides all the tools you need to use databases in your applications thanks to Doctrine, the best set of PHP libraries to work with databases. These tools support relational databases like MySQL and PostgreSQL and also NoSQL databases like MongoDB.

Databases are a broad topic, so the documentation is divided in three articles:

  • This article explains the recommended way to work with relational databases in Symfony applications;
  • Read this other article if you need low-level access to perform raw SQL queries to relational databases (similar to PHP’s PDO);
  • Read DoctrineMongoDBBundle docs if you are working with MongoDB databases.

Installing Doctrine

First, install Doctrine support via the orm Symfony pack, as well as the MakerBundle, which will help generate some code:

  1. $ composer require symfony/orm-pack
  2. $ composer require --dev symfony/maker-bundle

Configuring the Database

The database connection information is stored as an environment variable called DATABASE_URL. For development, you can find and customize this inside .env:

  1. # .env (or override DATABASE_URL in .env.local to avoid committing your changes)
  2. # customize this line!
  3. DATABASE_URL="mysql://db_user:[email protected]:3306/db_name?serverVersion=5.7"
  4. # to use mariadb:
  5. DATABASE_URL="mysql://db_user:[email protected]:3306/db_name?serverVersion=mariadb-10.5.8"
  6. # to use sqlite:
  7. # DATABASE_URL="sqlite:///%kernel.project_dir%/var/app.db"
  8. # to use postgresql:
  9. # DATABASE_URL="postgresql://db_user:[email protected]:5432/db_name?serverVersion=11&charset=utf8"
  10. # to use oracle:
  11. # DATABASE_URL="oci8://db_user:[email protected]:1521/db_name"

Caution

If the username, password, host or database name contain any character considered special in a URI (such as +, @, $, #, /, :, *, !), you must encode them. See RFC 3986 for the full list of reserved characters or use the urlencode function to encode them. In this case you need to remove the resolve: prefix in config/packages/doctrine.yaml to avoid errors: url: '%env(resolve:DATABASE_URL)%'

Now that your connection parameters are setup, Doctrine can create the db_name database for you:

  1. $ php bin/console doctrine:database:create

There are more options in config/packages/doctrine.yaml that you can configure, including your server_version (e.g. 5.7 if you’re using MySQL 5.7), which may affect how Doctrine functions.

Tip

There are many other Doctrine commands. Run php bin/console list doctrine to see a full list.

Creating an Entity Class

Suppose you’re building an application where products need to be displayed. Without even thinking about Doctrine or databases, you already know that you need a Product object to represent those products.

You can use the make:entity command to create this class and any fields you need. The command will ask you some questions - answer them like done below:

  1. $ php bin/console make:entity
  2. Class name of the entity to create or update:
  3. > Product
  4. New property name (press <return> to stop adding fields):
  5. > name
  6. Field type (enter ? to see all types) [string]:
  7. > string
  8. Field length [255]:
  9. > 255
  10. Can this field be null in the database (nullable) (yes/no) [no]:
  11. > no
  12. New property name (press <return> to stop adding fields):
  13. > price
  14. Field type (enter ? to see all types) [string]:
  15. > integer
  16. Can this field be null in the database (nullable) (yes/no) [no]:
  17. > no
  18. New property name (press <return> to stop adding fields):
  19. >
  20. (press enter again to finish)

New in version 1.3: The interactive behavior of the make:entity command was introduced in MakerBundle 1.3.

Woh! You now have a new src/Entity/Product.php file:

  1. // src/Entity/Product.php
  2. namespace App\Entity;
  3. use App\Repository\ProductRepository;
  4. use Doctrine\ORM\Mapping as ORM;
  5. /**
  6. * @ORM\Entity(repositoryClass=ProductRepository::class)
  7. */
  8. class Product
  9. {
  10. /**
  11. * @ORM\Id()
  12. * @ORM\GeneratedValue()
  13. * @ORM\Column(type="integer")
  14. */
  15. private $id;
  16. /**
  17. * @ORM\Column(type="string", length=255)
  18. */
  19. private $name;
  20. /**
  21. * @ORM\Column(type="integer")
  22. */
  23. private $price;
  24. public function getId(): ?int
  25. {
  26. return $this->id;
  27. }
  28. // ... getter and setter methods
  29. }

Note

Confused why the price is an integer? Don’t worry: this is just an example. But, storing prices as integers (e.g. 100 = $1 USD) can avoid rounding issues.

Note

If you are using an SQLite database, you’ll see the following error: PDOException: SQLSTATE[HY000]: General error: 1 Cannot add a NOT NULL column with default value NULL. Add a nullable=true option to the description property to fix the problem.

Caution

There is a limit of 767 bytes for the index key prefix when using InnoDB tables in MySQL 5.6 and earlier versions. String columns with 255 character length and utf8mb4 encoding surpass that limit. This means that any column of type string and unique=true must set its maximum length to 190. Otherwise, you’ll see this error: “[PDOException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes”.

This class is called an “entity”. And soon, you’ll be able to save and query Product objects to a product table in your database. Each property in the Product entity can be mapped to a column in that table. This is usually done with annotations: the @ORM\... comments that you see above each property:

_images/mapping_single_entity.png

The make:entity command is a tool to make life easier. But this is your code: add/remove fields, add/remove methods or update configuration.

Doctrine supports a wide variety of field types, each with their own options. To see a full list, check out Doctrine’s Mapping Types documentation. If you want to use XML instead of annotations, add type: xml and dir: '%kernel.project_dir%/config/doctrine' to the entity mappings in your config/packages/doctrine.yaml file.

Caution

Be careful not to use reserved SQL keywords as your table or column names (e.g. GROUP or USER). See Doctrine’s Reserved SQL keywords documentation for details on how to escape these. Or, change the table name with @ORM\Table(name="groups") above the class or configure the column name with thename=”group_name”` option.

Migrations: Creating the Database Tables/Schema

The Product class is fully-configured and ready to save to a product table. If you just defined this class, your database doesn’t actually have the product table yet. To add it, you can leverage the DoctrineMigrationsBundle, which is already installed:

  1. $ php bin/console make:migration

If everything worked, you should see something like this:

SUCCESS!

Next: Review the new migration “migrations/Version20180207231217.php” Then: Run the migration with php bin/console doctrine:migrations:migrate

If you open this file, it contains the SQL needed to update your database! To run that SQL, execute your migrations:

  1. $ php bin/console doctrine:migrations:migrate

This command executes all migration files that have not already been run against your database. You should run this command on production when you deploy to keep your production database up-to-date.

Migrations & Adding more Fields

But what if you need to add a new field property to Product, like a description? You can edit the class to add the new property. But, you can also use make:entity again:

  1. $ php bin/console make:entity
  2. Class name of the entity to create or update
  3. > Product
  4. New property name (press <return> to stop adding fields):
  5. > description
  6. Field type (enter ? to see all types) [string]:
  7. > text
  8. Can this field be null in the database (nullable) (yes/no) [no]:
  9. > no
  10. New property name (press <return> to stop adding fields):
  11. >
  12. (press enter again to finish)

This adds the new description property and getDescription() andsetDescription() methods:

  1. // src/Entity/Product.php
  2. // ...
  3. class Product
  4. {
  5. // ...
  6. + /**
  7. + * @ORM\Column(type="text")
  8. + */
  9. + private $description;
  10. // getDescription() & setDescription() were also added
  11. }

The new property is mapped, but it doesn’t exist yet in the product table. No problem! Generate a new migration:

  1. $ php bin/console make:migration

This time, the SQL in the generated file will look like this:

  1. ALTER TABLE product ADD description LONGTEXT NOT NULL

The migration system is smart. It compares all of your entities with the current state of the database and generates the SQL needed to synchronize them! Like before, execute your migrations:

  1. $ php bin/console doctrine:migrations:migrate

This will only execute the one new migration file, because DoctrineMigrationsBundle knows that the first migration was already executed earlier. Behind the scenes, it manages a migration_versions table to track this.

Each time you make a change to your schema, run these two commands to generate the migration and then execute it. Be sure to commit the migration files and execute them when you deploy.

Tip

If you prefer to add new properties manually, the make:entity command can generate the getter & setter methods for you:

  1. $ php bin/console make:entity --regenerate

If you make some changes and want to regenerate all getter/setter methods, also pass --overwrite.

Persisting Objects to the Database

It’s time to save a Product object to the database! Let’s create a new controller to experiment:

  1. $ php bin/console make:controller ProductController

Inside the controller, you can create a new Product object, set data on it, and save it:

  1. // src/Controller/ProductController.php
  2. namespace App\Controller;
  3. // ...
  4. use App\Entity\Product;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\HttpFoundation\Response;
  7. class ProductController extends AbstractController
  8. {
  9. /**
  10. * @Route("/product", name="create_product")
  11. */
  12. public function createProduct(): Response
  13. {
  14. // you can fetch the EntityManager via $this->getDoctrine()
  15. // or you can add an argument to the action: createProduct(EntityManagerInterface $entityManager)
  16. $entityManager = $this->getDoctrine()->getManager();
  17. $product = new Product();
  18. $product->setName('Keyboard');
  19. $product->setPrice(1999);
  20. $product->setDescription('Ergonomic and stylish!');
  21. // tell Doctrine you want to (eventually) save the Product (no queries yet)
  22. $entityManager->persist($product);
  23. // actually executes the queries (i.e. the INSERT query)
  24. $entityManager->flush();
  25. return new Response('Saved new product with id '.$product->getId());
  26. }
  27. }

Try it out!

http://localhost:8000/product

Congratulations! You just created your first row in the product table. To prove it, you can query the database directly:

  1. $ php bin/console doctrine:query:sql 'SELECT * FROM product'
  2. # on Windows systems not using Powershell, run this command instead:
  3. # php bin/console doctrine:query:sql "SELECT * FROM product"

Take a look at the previous example in more detail:

  • line 18 The `$this->getDoctrine()->getManager() method gets Doctrine’s entity manager object, which is the most important object in Doctrine. It’s responsible for saving objects to, and fetching objects from, the database.
  • lines 20-23 In this section, you instantiate and work with the $product object like any other normal PHP object.
  • line 26 The persist($product) call tells Doctrine to “manage” the$product` object. This does not cause a query to be made to the database.
  • line 29 When the flush() method is called, Doctrine looks through all of the objects that it’s managing to see if they need to be persisted to the database. In this example, the$productobject’s data doesn’t exist in the database, so the entity manager executes anINSERTquery, creating a new row in theproduct` table.

Note

If the flush() call fails, aDoctrine\ORM\ORMException` exception is thrown. See Transactions and Concurrency.

Whether you’re creating or updating objects, the workflow is always the same: Doctrine is smart enough to know if it should INSERT or UPDATE your entity.

Validating Objects

The Symfony validator reuses Doctrine metadata to perform some basic validation tasks:

  1. // src/Controller/ProductController.php
  2. namespace App\Controller;
  3. use App\Entity\Product;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\Validator\Validator\ValidatorInterface;
  6. // ...
  7. class ProductController extends AbstractController
  8. {
  9. /**
  10. * @Route("/product", name="create_product")
  11. */
  12. public function createProduct(ValidatorInterface $validator): Response
  13. {
  14. $product = new Product();
  15. // This will trigger an error: the column isn't nullable in the database
  16. $product->setName(null);
  17. // This will trigger a type mismatch error: an integer is expected
  18. $product->setPrice('1999');
  19. // ...
  20. $errors = $validator->validate($product);
  21. if (count($errors) > 0) {
  22. return new Response((string) $errors, 400);
  23. }
  24. // ...
  25. }
  26. }

Although the Product entity doesn’t define any explicit validation configuration, Symfony introspects the Doctrine mapping configuration to infer some validation rules. For example, given that the name property can’t be null in the database, a NotNull constraint is added automatically to the property (if it doesn’t contain that constraint already).

The following table summarizes the mapping between Doctrine metadata and the corresponding validation constraints added automatically by Symfony:

Doctrine attributeValidation constraintNotes
nullable=falseNotNullRequires installing the PropertyInfo component
typeTypeRequires installing the PropertyInfo component
unique=trueUniqueEntity 
lengthLength 

Because the Form component as well as API Platform internally use the Validator component, all your forms and web APIs will also automatically benefit from these automatic validation constraints.

This automatic validation is a nice feature to improve your productivity, but it doesn’t replace the validation configuration entirely. You still need to add some validation constraints to ensure that data provided by the user is correct.

Fetching Objects from the Database

Fetching an object back out of the database is even easier. Suppose you want to be able to go to /product/1 to see your new product:

  1. // src/Controller/ProductController.php
  2. namespace App\Controller;
  3. use App\Entity\Product;
  4. use Symfony\Component\HttpFoundation\Response;
  5. // ...
  6. class ProductController extends AbstractController
  7. {
  8. /**
  9. * @Route("/product/{id}", name="product_show")
  10. */
  11. public function show(int $id): Response
  12. {
  13. $product = $this->getDoctrine()
  14. ->getRepository(Product::class)
  15. ->find($id);
  16. if (!$product) {
  17. throw $this->createNotFoundException(
  18. 'No product found for id '.$id
  19. );
  20. }
  21. return new Response('Check out this great product: '.$product->getName());
  22. // or render a template
  23. // in the template, print things with {{ product.name }}
  24. // return $this->render('product/show.html.twig', ['product' => $product]);
  25. }
  26. }

Another possibility is to use the ProductRepository using Symfony’s autowiring and injected by the dependency injection container:

  1. // src/Controller/ProductController.php
  2. namespace App\Controller;
  3. use App\Entity\Product;
  4. use App\Repository\ProductRepository;
  5. use Symfony\Component\HttpFoundation\Response;
  6. // ...
  7. class ProductController extends AbstractController
  8. {
  9. /**
  10. * @Route("/product/{id}", name="product_show")
  11. */
  12. public function show(int $id, ProductRepository $productRepository): Response
  13. {
  14. $product = $productRepository
  15. ->find($id);
  16. // ...
  17. }
  18. }

Try it out!

http://localhost:8000/product/1

When you query for a particular type of object, you always use what’s known as its “repository”. You can think of a repository as a PHP class whose only job is to help you fetch entities of a certain class.

Once you have a repository object, you have many helper methods:

  1. $repository = $this->getDoctrine()->getRepository(Product::class);
  2. // look for a single Product by its primary key (usually "id")
  3. $product = $repository->find($id);
  4. // look for a single Product by name
  5. $product = $repository->findOneBy(['name' => 'Keyboard']);
  6. // or find by name and price
  7. $product = $repository->findOneBy([
  8. 'name' => 'Keyboard',
  9. 'price' => 1999,
  10. ]);
  11. // look for multiple Product objects matching the name, ordered by price
  12. $products = $repository->findBy(
  13. ['name' => 'Keyboard'],
  14. ['price' => 'ASC']
  15. );
  16. // look for *all* Product objects
  17. $products = $repository->findAll();

You can also add custom methods for more complex queries! More on that later in the Querying for Objects: The Repository section.

Tip

When rendering an HTML page, the web debug toolbar at the bottom of the page will display the number of queries and the time it took to execute them:

_images/doctrine_web_debug_toolbar.png

If the number of database queries is too high, the icon will turn yellow to indicate that something may not be correct. Click on the icon to open the Symfony Profiler and see the exact queries that were executed. If you don’t see the web debug toolbar, install the profiler Symfony pack by running this command: composer require --dev symfony/profiler-pack.

Automatically Fetching Objects (ParamConverter)

In many cases, you can use the SensioFrameworkExtraBundle to do the query for you automatically! First, install the bundle in case you don’t have it:

  1. $ composer require sensio/framework-extra-bundle

Now, simplify your controller:

  1. // src/Controller/ProductController.php
  2. namespace App\Controller;
  3. use App\Entity\Product;
  4. use App\Repository\ProductRepository;
  5. use Symfony\Component\HttpFoundation\Response;
  6. // ...
  7. class ProductController extends AbstractController
  8. {
  9. /**
  10. * @Route("/product/{id}", name="product_show")
  11. */
  12. public function show(Product $product): Response
  13. {
  14. // use the Product!
  15. // ...
  16. }
  17. }

That’s it! The bundle uses the {id} from the route to query for the Product by the id column. If it’s not found, a 404 page is generated.

There are many more options you can use. Read more about the ParamConverter.

Updating an Object

Once you’ve fetched an object from Doctrine, you interact with it the same as with any PHP model:

  1. // src/Controller/ProductController.php
  2. namespace App\Controller;
  3. use App\Entity\Product;
  4. use App\Repository\ProductRepository;
  5. use Symfony\Component\HttpFoundation\Response;
  6. // ...
  7. class ProductController extends AbstractController
  8. {
  9. /**
  10. * @Route("/product/edit/{id}")
  11. */
  12. public function update(int $id): Response
  13. {
  14. $entityManager = $this->getDoctrine()->getManager();
  15. $product = $entityManager->getRepository(Product::class)->find($id);
  16. if (!$product) {
  17. throw $this->createNotFoundException(
  18. 'No product found for id '.$id
  19. );
  20. }
  21. $product->setName('New product name!');
  22. $entityManager->flush();
  23. return $this->redirectToRoute('product_show', [
  24. 'id' => $product->getId()
  25. ]);
  26. }
  27. }

Using Doctrine to edit an existing product consists of three steps:

  1. fetching the object from Doctrine;
  2. modifying the object;
  3. calling `flush() on the entity manager.

You can call `$entityManager->persist($product), but it isn’t necessary: Doctrine is already “watching” your object for changes.

Deleting an Object

Deleting an object is very similar, but requires a call to the `remove() method of the entity manager:

  1. $entityManager->remove($product);
  2. $entityManager->flush();

As you might expect, the remove() method notifies Doctrine that you’d like to remove the given object from the database. TheDELETEquery isn’t actually executed until theflush() method is called.

Querying for Objects: The Repository

You’ve already seen how the repository object allows you to run basic queries without any work:

  1. // from inside a controller
  2. $repository = $this->getDoctrine()->getRepository(Product::class);
  3. $product = $repository->find($id);

But what if you need a more complex query? When you generated your entity with make:entity, the command also generated a ProductRepository class:

  1. // src/Repository/ProductRepository.php
  2. namespace App\Repository;
  3. use App\Entity\Product;
  4. use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
  5. use Doctrine\Persistence\ManagerRegistry;
  6. class ProductRepository extends ServiceEntityRepository
  7. {
  8. public function __construct(ManagerRegistry $registry)
  9. {
  10. parent::__construct($registry, Product::class);
  11. }
  12. }

When you fetch your repository (i.e. ->getRepository(Product::class)), it is *actually* an instance of *this* object! This is because of therepositoryClassconfig that was generated at the top of yourProduct` entity class.

Suppose you want to query for all Product objects greater than a certain price. Add a new method for this to your repository:

  1. // src/Repository/ProductRepository.php
  2. // ...
  3. class ProductRepository extends ServiceEntityRepository
  4. {
  5. public function __construct(ManagerRegistry $registry)
  6. {
  7. parent::__construct($registry, Product::class);
  8. }
  9. /**
  10. * @return Product[]
  11. */
  12. public function findAllGreaterThanPrice(int $price): array
  13. {
  14. $entityManager = $this->getEntityManager();
  15. $query = $entityManager->createQuery(
  16. 'SELECT p
  17. FROM App\Entity\Product p
  18. WHERE p.price > :price
  19. ORDER BY p.price ASC'
  20. )->setParameter('price', $price);
  21. // returns an array of Product objects
  22. return $query->getResult();
  23. }
  24. }

The string passed to createQuery() might look like SQL, but it is [Doctrine Query Language](https://www.doctrine-project.org/projects/doctrine-orm/en/current/reference/dql-doctrine-query-language.html). This allows you to type queries using commonly known query language, but referencing PHP objects instead (i.e. in theFROM` statement).

Now, you can call this method on the repository:

  1. // from inside a controller
  2. $minPrice = 1000;
  3. $products = $this->getDoctrine()
  4. ->getRepository(Product::class)
  5. ->findAllGreaterThanPrice($minPrice);
  6. // ...

See Injecting Services/Config into a Service for how to inject the repository into any service.

Querying with the Query Builder

Doctrine also provides a Query Builder, an object-oriented way to write queries. It is recommended to use this when queries are built dynamically (i.e. based on PHP conditions):

  1. // src/Repository/ProductRepository.php
  2. // ...
  3. class ProductRepository extends ServiceEntityRepository
  4. {
  5. public function findAllGreaterThanPrice(int $price, bool $includeUnavailableProducts = false): array
  6. {
  7. // automatically knows to select Products
  8. // the "p" is an alias you'll use in the rest of the query
  9. $qb = $this->createQueryBuilder('p')
  10. ->where('p.price > :price')
  11. ->setParameter('price', $price)
  12. ->orderBy('p.price', 'ASC');
  13. if (!$includeUnavailableProducts) {
  14. $qb->andWhere('p.available = TRUE');
  15. }
  16. $query = $qb->getQuery();
  17. return $query->execute();
  18. // to get just one result:
  19. // $product = $query->setMaxResults(1)->getOneOrNullResult();
  20. }
  21. }

Querying with SQL

In addition, you can query directly with SQL if you need to:

  1. // src/Repository/ProductRepository.php
  2. // ...
  3. class ProductRepository extends ServiceEntityRepository
  4. {
  5. public function findAllGreaterThanPrice(int $price): array
  6. {
  7. $conn = $this->getEntityManager()->getConnection();
  8. $sql = '
  9. SELECT * FROM product p
  10. WHERE p.price > :price
  11. ORDER BY p.price ASC
  12. ';
  13. $stmt = $conn->prepare($sql);
  14. $stmt->execute(['price' => $price]);
  15. // returns an array of arrays (i.e. a raw data set)
  16. return $stmt->fetchAllAssociative();
  17. }
  18. }

With SQL, you will get back raw data, not objects (unless you use the NativeQuery functionality).

Configuration

See the Doctrine config reference.

Relationships and Associations

Doctrine provides all the functionality you need to manage database relationships (also known as associations), including ManyToOne, OneToMany, OneToOne and ManyToMany relationships.

For info, see How to Work with Doctrine Associations / Relations.

Database Testing

Read the article about testing code that interacts with the database.

Doctrine Extensions (Timestampable, Translatable, etc.)

Doctrine community has created some extensions to implement common needs such as “set the value of the createdAt property automatically when creating an entity”. Read more about the available Doctrine extensions and use the StofDoctrineExtensionsBundle to integrate them in your application.

Learn more

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