Doctrine Cascade Options for OneToMany

后端 未结 2 868
粉色の甜心
粉色の甜心 2020-12-24 05:21

I\'m having a hard time making sense of the Doctrine manual\'s explanation of cascade operations and need someone to help me understand the options in terms of a simple Many

2条回答
  •  生来不讨喜
    2020-12-24 05:55

    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!

提交回复
热议问题