Doctrine Cascade Options for OneToMany

In the Doctrine2 documentation “9.6. Transitive persistence / Cascade Operations” there are few examples of how you should configure your entities so that when you persist $article, the $topic would be also persisted. In your case I’d suggest this annotation for Topic entity:

/**
 * @OneToMany(targetEntity="Article", mappedBy="topic", cascade={"persist", "remove"})
 */
 private $articles;  

The drawback of this solution is that you have to include $articles collection to Topic entity, but you can leave it private without getter/setter.

And as @kurt-krueckeberg mentioned, you must pass the real Topic entity when creating new Article, i.e.:

$topic = $em->getRepository('Entity\Topic')->find($id);
$article = new Article($topic);
$em->persist($article);
$em->flush();

// perhaps, in this case you don't even need to configure cascade operations

Good luck!

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)