How to ManyToMany and OneToMany in Symfony and Doctrine?

前端 未结 2 1934
臣服心动
臣服心动 2021-02-06 04:44

I find the documentation very poor when it comes to explaining the creation of relationships between entities. So, i\'ll have to ask for help to my fellow StackExchangers. So, i

2条回答
  •  再見小時候
    2021-02-06 05:25

    Try this:

    Class User {  
     /**
      * @ORM\OneToMany(targetEntity="path\to\group", mappedBy="user", cascade={"persist", "remove"})
      */
      private $group;
    

    You will have One to Many relation between User and Group.. The targetEntity is the path to the Entity that you want have a relationship with, the mappedBy is the variable from the Group Entity. cascade means User can add to Group and remove from Group

    Class Group {

    /**
     * @ORM\ManyToOne(targetEntity="path\to\user, inversedBy="group")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    private $user;
    

    This is the reserve side of the relationship.. targetEntity should have the path back to the parent entity, which is User in this case. inversedBy is the variable from the User Entity. JoinColumn is just telling Doctrine what to join on, this is automatically done if you don't set it yourself.

提交回复
热议问题