在doctrine 2 doc示例中,拥有方和反方是什么

mat*_*h88 15 php doctrine-orm

在这个关联映射页面上,有一个例子在manytomany部分.但我不明白哪个实体(组或用户)是拥有方.

http://docs.doctrine-project.org/en/2.0.x/reference/association-mapping.html#many-to-many-bidirectional

我也把代码放在这里

<?php
/** @Entity */
class User
{
    // ...

    /**
     * @ManyToMany(targetEntity="Group", inversedBy="users")
     * @JoinTable(name="users_groups")
     */
    private $groups;

    public function __construct() {
        $this->groups = new \Doctrine\Common\Collections\ArrayCollection();
    }

    // ...
}

/** @Entity */
class Group
{
    // ...
    /**
     * @ManyToMany(targetEntity="User", mappedBy="groups")
     */
    private $users;

    public function __construct() {
        $this->users = new \Doctrine\Common\Collections\ArrayCollection();
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

我是否读过这样的注释:用户是映射组,所以组是进行连接管理的实体,因此是拥有方?

另外,我在文档中读到过这个:

For ManyToMany bidirectional relationships either side may be the owning side (the side  that defines the @JoinTable and/or does not make use of the mappedBy attribute, thus using   a default join table).
Run Code Online (Sandbox Code Playgroud)

这让我认为User就是拥有者,因为JoinTable注释是在该实体中定义的.

Ped*_*iro 15

取自文档:

在一对一关系中,将相关实体的外键保存在其自己的数据库表上的实体始终是该关系的拥有方.

在多对一关系中,默认情况下,Many-side是拥有方,因为它拥有外键.默认情况下,关系的OneToMany端是反向的,因为外键保存在Many侧.OneToMany关系只能是拥有方,如果它使用与连接表的ManyToMany关系实现并且限制一侧只允许每个数据库约束的UNIQUE值.

现在,我理解ManyToMany有时会让人困惑.

对于多对多关联,您可以选择哪个实体是拥有者,哪个实体是反面.从开发人员的角度来看,有一个非常简单的语义规则来决定哪一方更适合作为拥有方.您只需要问自己,哪个实体负责连接管理,并选择作为拥有方.

以两个实体Article和Tag为例.每当您想要将文章连接到标签时,反之亦然,主要是文章负责这种关系.每当您添加新文章时,您都希望将其与现有标签或新标签相关联.您的createArticle表单可能会支持此概念并允许直接指定标记.这就是为什么你应该选择文章作为拥有方,因为它使代码更容易理解:

<?php
class Article
{
    private $tags;

    public function addTag(Tag $tag)
    {
        $tag->addArticle($this); // synchronously updating inverse side
        $this->tags[] = $tag;
    }
}

class Tag
{
    private $articles;

    public function addArticle(Article $article)
    {
        $this->articles[] = $article;
    }
}
Run Code Online (Sandbox Code Playgroud)

这允许在关联的Article侧添加标记:

<?php
$article = new Article();
$article->addTag($tagA);
$article->addTag($tagB);
Run Code Online (Sandbox Code Playgroud)

所以,简而言之,无论什么对你更有意义.您选择拥有和关系的反面.:)

资料来源:http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html


man*_*nix 15

但我不明白哪个实体(组或用户)是拥有方

User实体是所有者.您在用户中拥有组的关系:

/**
 * @ManyToMany(targetEntity="Group", inversedBy="users")
 * @JoinTable(name="users_groups")
 */
private $groups;
Run Code Online (Sandbox Code Playgroud)

在上面看,$groupsvar包含与此用户关联的所有组,但是如果您注意到属性定义,则$groupsvar具有相同mappedBy名称(mappedBy =" groups"),如下所示:

/**
 * @ManyToMany(targetEntity="User", mappedBy="groups")
 */
private $users;
Run Code Online (Sandbox Code Playgroud)

mappedBy是什么意思?

此选项指定targetEntity上的属性名称,该属性是此关系的拥有方.

  • 完美的解释 (2认同)