Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 62 ยท Databases with Doctrine

Relations

Link entities with Doctrine relations: ManyToOne, OneToMany and ManyToMany, the owning side, cascade and orphanRemoval, with a runnable SQLite stand-in.

Real data is connected. A blog post has comments, a comment has an author, a post has tags and a tag belongs to many posts. In a relational database these links are foreign keys and join tables. In Doctrine you describe them on your entity classes, and the ORM turns the links into real PHP objects: $post->getComments() gives you the comments, and $comment->getPost() gives you the post.

Relations are also where most Doctrine confusion lives, mainly around one question: which side of the relation actually writes to the database? This lesson answers it, then covers the three relation types, cascade and orphanRemoval. Doctrine cannot run here, so the real mapping code is read-only, and the runnable examples use plain PHP and SQLite to show the same behavior.

The three relation types

Doctrine offers ManyToOne, OneToMany, ManyToMany and OneToOne. The first three cover nearly everything.

erDiagram
    POST ||--o{ COMMENT : "has many"
    POST }o--o{ TAG : "post_tag"
    COMMENT {
        int id
        int post_id "foreign key"
        string body
    }
    POST {
        int id
        string title
    }
    TAG {
        int id
        string name
    }

One post has many comments through a foreign key on comment; posts and tags are linked through a join table.

  • ManyToOne: many comments point to one post. The foreign key (post_id) lives in the comment table.
  • OneToMany: the same relation seen from the post: one post has many comments. It is always the mirror of a ManyToOne, and has no column of its own.
  • ManyToMany: posts and tags. SQL needs a third table (the join table) holding pairs of ids. Doctrine creates and fills it for you.
  • OneToOne: for example a user and a profile. Rare, and often better as plain columns or an embeddable.

ManyToOne and OneToMany

Here are the two entities of a post and its comments, written the way make:entity generates them (shortened):

PHP
<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
class Comment
{
    #[ORM\Id, ORM\GeneratedValue, ORM\Column]
    private ?int $id = null;

    #[ORM\Column(type: 'text')]
    private string $body = '';

    #[ORM\ManyToOne(inversedBy: 'comments')]
    #[ORM\JoinColumn(nullable: false)]
    private ?Post $post = null;

    public function getPost(): ?Post
    {
        return $this->post;
    }

    public function setPost(?Post $post): static
    {
        $this->post = $post;

        return $this;
    }
}

Now the Post side, the inverse side that holds the collection:

PHP
<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
class Post
{
    #[ORM\Id, ORM\GeneratedValue, ORM\Column]
    private ?int $id = null;

    /** @var Collection<int, Comment> */
    #[ORM\OneToMany(mappedBy: 'post', targetEntity: Comment::class, cascade: ['persist'], orphanRemoval: true)]
    private Collection $comments;

    public function __construct()
    {
        $this->comments = new ArrayCollection();
    }

    /** @return Collection<int, Comment> */
    public function getComments(): Collection
    {
        return $this->comments;
    }

    public function addComment(Comment $comment): static
    {
        if (!$this->comments->contains($comment)) {
            $this->comments->add($comment);
            $comment->setPost($this);
        }

        return $this;
    }

    public function removeComment(Comment $comment): static
    {
        if ($this->comments->removeElement($comment)) {
            if ($comment->getPost() === $this) {
                $comment->setPost(null);
            }
        }

        return $this;
    }
}

Three details matter. The collection property must be initialized in the constructor with an ArrayCollection, because a brand-new entity has no database yet to fill it. mappedBy: 'post' names the property on Comment that owns the link. And addComment() sets both sides, which brings us to the key rule.

The owning side decides what is saved

In every bidirectional relation, Doctrine designates one side as owning and the other as inverse. The owning side is the one that has the foreign key column or controls the join table. Doctrine looks only at the owning side when it writes to the database. Changes made only on the inverse side are silently ignored.

  • In ManyToOne / OneToMany, the ManyToOne side (Comment::$post) is always the owning side. It uses inversedBy. The OneToMany side uses mappedBy.
  • In ManyToMany, you choose: the side with inversedBy owns, the side with mappedBy is the inverse.

This is why addComment() above also calls $comment->setPost($this). If you only did $post->getComments()->add($comment), the comment's post property would stay null and Doctrine would either fail with a NOT NULL error or save a comment with no post. The next stand-in reproduces exactly that trap with PDO. A persist function acts like Doctrine's unit of work: it writes post_id only from the owning side.

PHP Why the inverse side does not save (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The comment added the wrong way ends up with post_id NULL: the inverse side alone is invisible to the writer. Always add the synchronizing "adder" and "remover" methods, and make:entity generates them for you.

ManyToMany

For posts and tags, both sides hold collections and Doctrine manages a join table named after the two entities (post_tag). The owning side adds the inversedBy option:

PHP
// Post.php (owning side)
#[ORM\ManyToMany(targetEntity: Tag::class, inversedBy: 'posts')]
private Collection $tags;

// Tag.php (inverse side)
#[ORM\ManyToMany(targetEntity: Post::class, mappedBy: 'tags')]
private Collection $posts;

Adding a tag is $post->addTag($tag); Doctrine inserts one row into post_tag on flush, and removes it when you call removeTag(). The stand-in below does the same by hand and shows the join table.

A pure ManyToMany has no room for extra data. If you need "when was the tag added" or "who added it", the relation has become a thing of its own. Model it as a third entity (for example PostTag with two ManyToOne relations and a createdAt column) instead of a ManyToMany.

cascade and orphanRemoval

By default Doctrine does not follow relations when you persist or remove an object. If you persist a Post that holds a new Comment, you must also persist the comment, otherwise flush fails with a "new entity found through a relationship" error. Two options change that:

  • cascade: ['persist'] persists related objects together with the owner. Add remove to delete them with it.
  • orphanRemoval: true deletes a child row when it is removed from the parent's collection, because a comment without a post makes no sense.

Use these only on relations where the child belongs to the parent and has no independent life. A comment belongs to a post. A tag does not belong to one post, so cascading remove on tags would delete a tag that other posts still use.

There is also a database-level option: #[ORM\JoinColumn(onDelete: 'CASCADE')] makes the database itself delete child rows when the parent row is deleted. It is faster for big deletes, but Doctrine does not know it happened, so objects you already loaded can become stale.

The stand-in below builds a join table and an orphan-removal rule on SQLite:

PHP Join table and orphan removal (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

You can navigate relations as plain properties: {{ post.comments|length }} in Twig or $post->getComments()->count() in PHP. The first access to a collection runs an extra query, which is convenient but has a cost when you loop over many posts. That trap (the N+1 problem) and its cure, joins in your repository, are the subject of Doctrine Performance and Pitfalls.

Two more tools are worth knowing. Because make:entity can add a relation for you through its interactive prompts (php bin/console make:entity Comment, then add a field of type relation), you rarely hand-write the attributes. And after any mapping change you generate a migration with make:migration, as covered in Migrations.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a bidirectional ManyToOne / OneToMany relation, which side is the owning side?

    The ManyToOne side owns the relation because the foreign key column lives in its table. The OneToMany side is the inverse and uses mappedBy.
  2. 2. You add a Comment only with $post->getComments()->add($comment) and flush. What is likely to happen?

    Doctrine reads only the owning side. Without $comment->setPost($post) the foreign key stays empty, so use an addComment() helper that sets both sides.
  3. 3. What does orphanRemoval: true do on a OneToMany relation?

    A child that is detached from its parent is an orphan, and Doctrine deletes it on flush.
  4. 4. When should you model a many-to-many link as its own entity?

    A join table that Doctrine manages has only the two foreign keys. Extra columns require an association entity with two ManyToOne relations.
  5. 5. Why is cascade: ['remove'] on a Post-to-Tag ManyToMany a bad idea?

    Tags are shared. Cascade remove belongs on relations where the child is owned by the parent, like comments on a post.

Summary

  • ManyToOne holds the foreign key and is the owning side; OneToMany is its inverse and uses mappedBy.
  • ManyToMany uses a join table; pick the owning side with inversedBy. Extra data on the link needs a separate entity.
  • Doctrine writes only the owning side, so adder and remover methods must set both sides.
  • Initialize collections in the constructor with ArrayCollection.
  • Use cascade and orphanRemoval only when the child truly belongs to its parent.

Next up: Doctrine Performance and Pitfalls.