Learn Symfony · 4/12

Database Mastery with Doctrine ORM

10 min read

Welcome to the heart of data management in Symfony. Almost every application needs to store, retrieve, and manipulate data. In the modern PHP ecosystem, we rarely write raw SQL queries by hand. Instead, we use a powerful tool called Doctrine.

Let us break down how Doctrine works, piece by piece, so you can confidently manage your application's data.


1. Understanding ORM and Configuring Doctrine Connections 🔌

Definition

An ORM (Object-Relational Mapping) is a programming technique and a library that maps application objects (like PHP classes) to relational database tables (like MySQL or PostgreSQL). Doctrine is the default ORM used in the Symfony framework.

The Problem

Historically, interacting with a database required writing raw SQL queries as strings inside your code (e.g., SELECT * FROM users WHERE status = 'active'). This approach presents several massive problems:

  1. Security: If not handled perfectly, raw SQL strings are highly vulnerable to SQL injection attacks.
  2. Maintenance: If you rename a database column, you have to manually hunt down and update every SQL string in your codebase.
  3. Database Lock-in: SQL dialects differ slightly between MySQL, PostgreSQL, and SQLite. If you want to switch database engines, you have to rewrite your queries.
  4. Data Conversion: Databases return raw arrays of strings and numbers. You have to manually convert these rows into structured PHP objects every single time.

The Solution

Doctrine ORM solves this by acting as an abstraction layer. Instead of writing SQL, you write standard PHP code. You create a PHP object, set its properties, and tell Doctrine to "save" it. Doctrine automatically generates the correct SQL, sanitizes the data, executes the query, and converts the results back into PHP objects when you need them.

How it flows: Imagine you are managing a massive warehouse (the database). If you personally run to the shelves to find every single item (writing raw SQL), you will exhaust yourself. Doctrine is your automated warehouse manager. You simply hand the manager a standardized request slip (a PHP object), and they figure out the safest, fastest path to store or retrieve the item.

Industry Setup & Configuration

To get started in a modern Symfony application, we install the ORM pack. Open your terminal and run:

bash
composer require symfony/orm-pack
composer require --dev symfony/maker-bundle

Once installed, Doctrine needs to know how to connect to your database. Symfony uses environment variables for this. Open your .env file (located in the root of your project) and look for the DATABASE_URL variable.

env
# .env
# For a MySQL/MariaDB database:
DATABASE_URL="mysql://db_user:[email protected]:3306/my_database_name?serverVersion=8.0.32&charset=utf8mb4"

# For a PostgreSQL database:
# DATABASE_URL="postgresql://db_user:[email protected]:5432/my_database_name?serverVersion=16&charset=utf8"

Once your credentials are correct, you can instruct Doctrine to create the actual database on your database server:

bash
php bin/console doctrine:database:create

Fun Fact: Doctrine is so smart that if you ever decide to switch from MySQL to PostgreSQL, you usually only need to change this one DATABASE_URL line. Doctrine translates your PHP code into the correct SQL dialect automatically!


2. Entities: Mapping PHP Classes to Database Tables 🗺️

Definition

An Entity is a standard PHP class whose properties are explicitly mapped to columns in a specific database table. An instance (object) of this class represents a single row in that table.

The Problem

Databases understand tables, rows, and columns. PHP understands classes, objects, and properties. Without a predefined map, Doctrine has no idea that your Product PHP class is supposed to save its data into a database table named products, or that the $price property should be an integer.

The Solution

We use PHP Attributes to provide metadata to Doctrine. By attaching #\[ORM\Entity\] above a class, and #\[ORM\Column\] above a property, we explicitly teach Doctrine the rules for translating our PHP class into a database table.

Practical Usage

In industry, nobody writes Entities completely from scratch because it is highly repetitive. We use Symfony's Maker Bundle to generate them interactively.

Run this command:

bash
php bin/console make:entity Product

The terminal will ask you to add properties one by one. You type name, tell it the type is string, and set the length to 255. Then you type price, set it to integer, and so on.

Symfony will generate a file in src/Entity/Product.php that looks like this:

php
namespace App\Entity;

use App\Repository\ProductRepository;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: ProductRepository::class)]
class Product
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 255)]
    private ?string $name = null;

    #[ORM\Column]
    private ?int $price = null;

    // Getters and Setters are auto-generated below...
    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): static
    {
        $this->name = $name;
        return $this;
    }
}

Notice the properties are private. Doctrine uses PHP Reflection to access them, but for your application code to read or modify these values, Symfony auto-generates public "getter" and "setter" methods.


3. Database Migrations: Version Control for Your Schema 🏗️

Definition

Database Migrations are auto-generated PHP classes that contain the exact SQL statements needed to update your database schema (tables, columns, indexes) from its current state to a new state.

The Problem

As you build your application, your Entities will change. Today, a Product just has a name and price. Tomorrow, your boss asks you to add a description column. If you manually run an ALTER TABLE SQL command on your local machine, how does your coworker get that same update? How does the production server know about it? Manually tracking database changes leads to fatal crashes when code expects a column that does not exist.

The Solution

Migrations solve this by treating database changes exactly like Git treats code changes. When you modify an Entity, Doctrine compares your PHP code to your actual database, detects the differences, and writes a step-by-step SQL script (a migration) to safely apply the changes.

How it flows: Imagine building an office building. Migrations are the blueprints for each renovation phase. Migration 1 lays the foundation (creates tables). Migration 2 adds a cafeteria (adds a new table). Migration 3 widens the hallways (increases a column's string length). If a new contractor joins the team, they just read and apply the blueprints in order to perfectly replicate the building.

Practical Usage

Whenever you create or update an Entity using make:entity, you must generate a migration:

bash
php bin/console make:migration

This looks at your Entities, realizes "Ah, the Product entity has a new $description property that isn't in the database yet!", and generates a file in the migrations/ folder.

To actually execute that SQL against your database, you run:

bash
php bin/console doctrine:migrations:migrate

⚠️ Industry Standard Rule: Never manually edit an existing, previously-run migration file. If you make a mistake, change your Entity again and generate a new migration. Migrations must always roll forward.


4. Repositories: Fetching and Querying Your Data 🔍

Definition

A Repository is a PHP class dedicated solely to retrieving Entities from the database. Every Entity type has exactly one dedicated Repository class.

The Problem

If you need to find all products that cost less than $50, you could write that query logic directly inside your Controller. However, if you later need that exact same logic in a background command (like a nightly email script), you would have to duplicate the code. This violates the DRY (Don't Repeat Yourself) principle and makes your code messy.

The Solution

Repositories centralize all read-operations. By placing all queries related to Product inside the ProductRepository, you create a clean, reusable library of queries that any part of your application can utilize.

Practical Usage

When you ran make:entity Product, Symfony automatically created src/Repository/ProductRepository.php.

To use it in a Controller, you simply ask for it using Dependency Injection (typing the repository class in your method arguments):

php
namespace App\Controller;

use App\Entity\Product;
use App\Repository\ProductRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class ProductController extends AbstractController
{
    #[Route('/products', name: 'product_list')]
    public function index(ProductRepository $productRepository): Response
    {
        // 1. Built-in method: Find all products
        $allProducts = $productRepository->findAll();

        // 2. Built-in method: Find one product by its ID
        $singleProduct = $productRepository->find(1);

        // 3. Built-in method: Find all products matching a specific criteria
        $cheapProducts = $productRepository->findBy(['price' => 10]);

        return $this->render('product/index.html.twig', [
            'products' => $allProducts,
        ]);
    }
}

Custom Queries with QueryBuilder:
When built-in methods are not enough (e.g., finding products priced greater than $50), you write custom methods inside your ProductRepository using Doctrine's QueryBuilder:

php
// src/Repository/ProductRepository.php

public function findExpensiveProducts(int $minPrice): array
{
    return $this->createQueryBuilder('p') // 'p' is an alias for Product
        ->andWhere('p.price > :minPrice')
        ->setParameter('minPrice', $minPrice)
        ->orderBy('p.price', 'ASC')
        ->setMaxResults(10)
        ->getQuery()
        ->getResult();
}

You can now call $productRepository->findExpensiveProducts(50) from anywhere in your app!


5. Data Relationships: OneToMany, ManyToOne, and ManyToMany 🤝

Definition

Data Relationships define how different Entities (and their corresponding database tables) interact and link with each other using foreign keys.

The Problem

Data in the real world is almost never isolated. A User makes Orders. An Order contains Products. If you tried to store all user data inside the Order table, you would duplicate the user's email address every time they ordered something. If they update their email, you would have to update thousands of rows.

The Solution

Relational databases solve this by splitting data into multiple tables and linking them via IDs (Foreign Keys). Doctrine maps these foreign keys into simple PHP object properties or collections (arrays), abstracting the complicated SQL joins away from you.

How it flows: Think of a restaurant. A table (Category) has many customers (Products). The customers belong to that specific table. You wouldn't merge the table and the customers into one giant entity; you keep them separate but note which table the customers are sitting at.

The Three Main Relationships in Industry

1. ManyToOne / OneToMany (The most common!)

Use this when many items belong to one item.
Example: Many Products belong to one Category.

In Doctrine, ManyToOne and OneToMany are two sides of the same coin.

  • The ManyToOne side (Product) is the "owning side". It physically holds the category_id column in the database.
  • The OneToMany side (Category) is the "inverse side". It doesn't hold a database column for this link; it just asks Doctrine to fetch all Products that have its ID.

To create this, just run php bin/console make:entity Product, type a new property name like category, and when asked for the type, type relation. The Maker bundle will guide you through setting up a ManyToOne relationship!

php
// Inside Product.php (The Many side - holds the foreign key)
#[ORM\ManyToOne(inversedBy: 'products')]
#[ORM\JoinColumn(nullable: false)]
private ?Category $category = null;

// Inside Category.php (The One side - holds a collection of Products)
#[ORM\OneToMany(targetEntity: Product::class, mappedBy: 'category')]
private Collection $products;

2. ManyToMany

Use this when many items belong to many other items.
Example: Students and Courses. A student takes many courses, and a course has many students.

To make this work in SQL, you normally need a secret third table (a "pivot table"). The beauty of Doctrine is that if you tell Maker to create a ManyToMany relation, Doctrine creates and manages the pivot table automatically. You never even have to write a PHP class for it. You just deal with $student->getCourses() and $course->getStudents().

3. OneToOne (Less common)

Use this when one item belongs strictly to one other item.
Example: A User and a UserPreferences profile.

Working with Relationships in Code

Because Doctrine converts everything to objects, reading related data feels like magic. No JOIN queries required!

php
// If you have a $product object, fetching its category is this simple:
$categoryName = $product->getCategory()->getName();

// If you have a $category object, getting all its products:
$products = $category->getProducts(); // Returns a collection of Product objects
foreach ($products as $product) {
    echo $product->getName();
}

Doctrine handles the database queries behind the scenes the exact moment you call getCategory() or getProducts(). This is known as "Lazy Loading".


📚 Extra Reading & References

To deepen your mastery, keep these official resources bookmarked. They are the industry gold standard for daily Symfony development:

Challenge

Doctrine ORM: Entities, Relationships, and Repositories

You are tasked with modeling a basic inventory system using Doctrine ORM. You will need to create two related entities, Product and Category, and then implement a custom query method in the ProductRepository.

Requirements:

1. The Category Entity:

  • It must be a Doctrine entity.
  • It needs an auto-incrementing integer id as its primary key.
  • It needs a name property of type string with a maximum length of 255. This name must be unique in the database.
  • It must define the inverse side of a relationship with Product, holding a collection of all products that belong to it. The property should be named products.

2. The Product Entity:

  • It must be a Doctrine entity linked to the ProductRepository.
  • It needs an auto-incrementing integer id as its primary key.
  • It needs a name property of type string (length 255) and a price of type float.
  • It needs a stock property of type integer which cannot be null.
  • It must define the owning side of a Many-To-One relationship to the Category entity. This property should be named category and it should not be nullable. Ensure Doctrine cascades removal operations to this relation.

3. The ProductRepository Method:

  • Implement the findInStockByMinPrice method.
  • This method must use the QueryBuilder.
  • It should return an array of Product objects where the stock is greater than 0 AND the price is greater than or equal to the $minPrice parameter.
  • The results must be ordered by price in descending order.

Expected result

Your final code should consist of three fully implemented PHP constructs:

  1. A Category class decorated with Doctrine's #[ORM\Entity] attribute. It must contain:

    • An id property with #[ORM\Id], #[ORM\GeneratedValue], and #[ORM\Column] attributes.
    • A name property with #[ORM\Column(type: 'string', length: 255, unique: true)].
    • A products property with the #[ORM\OneToMany(mappedBy: 'category', targetEntity: Product::class, orphanRemoval: true)] attribute, initialized as an ArrayCollection in the constructor.
    • Appropriate public getter methods for all properties.
  2. A Product class decorated with #[ORM\Entity(repositoryClass: ProductRepository::class)]. It must contain:

    • An id property with #[ORM\Id], #[ORM\GeneratedValue], and #[ORM\Column] attributes.
    • name, price, and stock properties with the correct #[ORM\Column] types.
    • A category property with the #[ORM\ManyToOne(inversedBy: 'products')] and #[ORM\JoinColumn(nullable: false)] attributes.
    • Appropriate public getter and setter methods.
  3. A ProductRepository class where the findInStockByMinPrice method is implemented using the QueryBuilder. The implementation should correctly use:

    • createQueryBuilder('p')
    • andWhere() to filter by stock and price.
    • setParameter() to bind the :minPrice value.
    • orderBy('p.price', 'DESC')
    • getQuery() and getResult() to execute the query and return the results.
php

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.