How to ManyToMany and OneToMany in Symfony and Doctrine?

前端 未结 2 1932
臣服心动
臣服心动 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:28

    Sure thing. First thing to understand is that there is no "one way" to do this. Doctrine gives a lot of flexibility in terms of how you define the relationship - even if multiple definitions produce the exact same DDL (and this is important to understand - some of the mapping choices only effect the object-side of the ORM, not the model-side)

    Here's your Users/Groups/Permissions example, which are actually all many-to-many associations (I excluded all non-relevant but required code, like PK column definition)

    groups = new ArrayCollection();
        $this->permissions = new ArrayCollection();
      }
    }
    
    /**
     * @ORM\Entity
     */
    class Group
    {
      /**
       * Many-To-Many, Unidirectional
       *
       * @var ArrayCollection $permissions
       *
       * @ORM\ManyToMany(targetEntity="Permission")
       * @ORM\JoinTable(name="group_has_permission",
       *      joinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id")},
       *      inverseJoinColumns={@ORM\JoinColumn(name="permission_id", referencedColumnName="id")}
       * )
       */
      protected $permissions;
    
      public function __construct()
      {
        $this->permissions = new ArrayCollection();
      }
    }
    
    /**
     * @ORM\Entity
     */
    class Permission {}
    

    If you have questions about what's going on here, let me know.

    Now, to your second example

    tags = new ArrayCollection();
        $this->comments = new ArrayCollection();
      }
    }
    
    /**
     * @ORM\Entity
     */
    class Comment
    {
      /**
       * Many-To-One, Bidirectional
       *
       * @var Ticket $ticket
       *
       * @ORM\ManyToOne(targetEntity="Ticket")
       * @ORM\JoinColumn(name="ticket_id", referencedColumnName="id")
       */
      protected $ticket=null;
    }
    
    /**
     * @ORM\Entity
     */
    class Tag {}
    
    /**
     * @ORM\Entity
     */
    class Category {}
    

    As before, let me know if you want any of this explained.

    P.S. None of this was actually tested, I just kinda banged it out in my IDE real fast. There might be a typo or two ;)

提交回复
热议问题