sajad torkamani

What does cascade: ['persist'] do?

Suppose you have a User entity in Doctrine and that entity has one or more Article entities via an articles relationship:

class User {
    #[ORM\OneToMany(targetEntity: Article::class, mappedBy: 'user')]
    private Collection $articles;
}

If you create a new User entity with some Article entities like so:

$user = new User()
    ->setName('John Doe');

$article = new Article()
    ->setTitle('Some title')
    ->setContent('Some content');

$user->addArticle($article);

$this->entityManager->persist($user);
$this->entityManager->flush();

You’ll get the following exception:

cascade: ['persist'] in Doctrine

As the error message in the above screenshot suggests, you can do one of two things here:

  • Explicitly call EntityManager::persist() on the $article entity, or
  • Use the cascade: ['persist'] option to enable persistence of the User::articles field automatically when a User entity is persisted.

So we can fix the above error by adding the cascade: ['persist'] option like so:

How does cascade: ['persist'] work under the hood?

Because you added cascade: ['persist'],when Doctrine executes the below code:

$user = new User()
    ->setName('John Doe');

$article = new Article()
    ->setTitle('Some title')
    ->setContent('Some content');

$user->addArticle($article);

$this->entityManager->persist($user);
$this->entityManager->flush();

A the point it executes $this->entityManager->persist($user), Doctrine will also loop over the $user record’s articles and call EntityManager::persist() on each of those articles.

How is cascade: ['persist'] different from cascade: ['remove']?

cascade: ['persist']: Ensures that related entities are also persisted when the parent entity is persisted (User in the above example).

cascade: ['remove']: Ensure that related entities are also removed when the parent entity is removed. For example, if you wanted all articles of a user to be removed when you remove the owning user, you might add the following:

cascade: ['remove'] in Doctrine