在解释实体之间关系的创建时,我发现文档很差.所以,我将不得不向我的StackExchangers同事寻求帮助.所以,我正在尝试构建以下案例:
情况1
用户属于一个或多个组,组可以拥有多个权限.用户也可以拥有权限.
案例2
票证具有类别,多个标记和多个注释.
提前致谢!
当然可以.首先要明白的是,没有“单向”可以做到这一点. Doctrine在
define the relationship方面提供了很大的灵活性 – 即使多个定义产生完全相同的DDL(理解这一点很重要 – 一些映射选择只影响ORM的对象端,而不是模型端) )
这是您的用户/组/权限示例,实际上是所有多对多关联(我排除了所有不相关但必需的代码,如PK列定义)
<?PHP namespace Your\Bundle\Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; /** * @ORM\Entity */ class User { /** * Many-To-Many,Unidirectional * * @var ArrayCollection $groups * * @ORM\ManyToMany(targetEntity="Group") * @ORM\JoinTable(name="user_has_group",* joinColumns={@ORM\JoinColumn(name="user_id",referencedColumnName="id")},* inverseJoinColumns={@ORM\JoinColumn(name="group_id",referencedColumnName="id")} * ) */ protected $groups; /** * Many-To-Many,Unidirectional * * @var ArrayCollection $permissions * * @ORM\ManyToMany(targetEntity="Permission") * @ORM\JoinTable(name="user_has_permission",* inverseJoinColumns={@ORM\JoinColumn(name="permission_id",referencedColumnName="id")} * ) */ protected $permissions; public function __construct() { $this->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")} * ) */ protected $permissions; public function __construct() { $this->permissions = new ArrayCollection(); } } /** * @ORM\Entity */ class Permission {}
如果您对此处发生的事情有疑问,请与我们联系.
现在,到你的第二个例子
<?PHP namespace Your\Bundle\Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; /** * @ORM\Entity */ class Ticket { /** * Many-To-One,Unidirectional * * @var Category * * @ORM\ManyToOne(targetEntity="Category") * @ORM\JoinColumn(name="category_id",referencedColumnName="id") */ protected $category; /** * Many-To-Many,Unidirectional * * @var ArrayCollection $permissions * * @ORM\ManyToMany(targetEntity="Tag") * @ORM\JoinTable(name="tickt_has_tag",* joinColumns={@ORM\JoinColumn(name="ticket_id",* inverseJoinColumns={@ORM\JoinColumn(name="tag_id",referencedColumnName="id")} * ) */ protected $tags; /** * One-To-Many,Bidirectional * * @var ArrayCollection $comments * * @ORM\OneToMany(targetEntity="Comment",mappedBy="ticket") */ protected $comments; public function __construct() { $this->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 {}
和以前一样,如果你想要解释的话,请告诉我.
附:这些都没有经过实际测试,我只是快速地在我的IDE中将它击败了.可能有一两个错字;)