沃梦达 / 编程问答 / php问题 / 正文

Doctrine 的多对多自引用和互惠

Doctrine#39;s Many-To-Many Self-Referencing and reciprocity(Doctrine 的多对多自引用和互惠)

本文介绍了Doctrine 的多对多自引用和互惠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,Doctrine 下的自引用 ManyToMany 关系涉及拥有方和反向方,如 文档.

By default, self-referencing ManyToMany relationships under Doctrine involve an owning side and an inverse side, as explained in the documentation.

有没有办法实现互惠关联,双方之间没有区别?

Is there a way to implement a reciprocal association whithout difference between both sides?

按照文档中的示例:

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

    /**
     * @ManyToMany(targetEntity="User")
     **/
    private $friends;

    public function __construct() {
        $this->friends = new DoctrineCommonCollectionsArrayCollection();
    }

    // ...
}

因此,将 entity1 添加到 entity2friends 意味着 entity2 将在 entity1的朋友.

So, adding entity1 to entity2s friends implies that entity2 will be in entity1s friends.

推荐答案

有很多方法可以解决这个问题,都取决于对朋友"关系的要求.

There are a number of ways to solve this problem, all depending on what the requirements for the "friends" relation are.

单向

一种简单的方法是使用单向多对多关联,并将其视为双向关联(保持双方同步):

A simple approach would be to use a unidirectional ManyToMany association, and treat it as if it where a bidirectional one (keeping both sides in sync):

/**
 * @Entity
 */
class User
{
    /**
     * @Id
     * @Column(type="integer")
     */
    private $id;

    /**
     * @ManyToMany(targetEntity="User")
     * @JoinTable(name="friends",
     *     joinColumns={@JoinColumn(name="user_a_id", referencedColumnName="id")},
     *     inverseJoinColumns={@JoinColumn(name="user_b_id", referencedColumnName="id")}
     * )
     * @var DoctrineCommonCollectionsArrayCollection
     */
    private $friends;

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->friends = new DoctrineCommonCollectionsArrayCollection();
    }

    /**
     * @return array
     */
    public function getFriends()
    {
        return $this->friends->toArray();
    }

    /**
     * @param  User $user
     * @return void
     */
    public function addFriend(User $user)
    {
        if (!$this->friends->contains($user)) {
            $this->friends->add($user);
            $user->addFriend($this);
        }
    }

    /**
     * @param  User $user
     * @return void
     */
    public function removeFriend(User $user)
    {
        if ($this->friends->contains($user)) {
            $this->friends->removeElement($user);
            $user->removeFriend($this);
        }
    }

    // ...

}

当你调用$userA->addFriend($userB)时,$userB会被添加到$userA, $userA 将被添加到 $userB 中的好友集合中.

When you call $userA->addFriend($userB), $userB will be added to the friends-collection in $userA, and $userA will be added to the friends-collection in $userB.

这也会导致 2 条记录添加到朋友"表中(1,2 和 2,1).虽然这可以被视为重复数据,但它会大大简化您的代码.例如当你需要查找$userA的所有好友时,你可以简单地这样做:

It will also result in 2 records added to the "friends" table (1,2 and 2,1). While this can be seen as duplicate data, it will simplify your code a lot. For example when you need to find all friends of $userA, you can simply do:

SELECT u FROM User u JOIN u.friends f WHERE f.id = :userId

无需像使用双向关联那样检查 2 个不同的属性.

No need to check 2 different properties as you would with a bidirectional association.

双向

当使用双向关联时,User 实体将具有 2 个属性,例如 $myFriends$friendsWithMe.您可以按照上述相同的方式使它们保持同步.

When using a bidirectional association the User entity will have 2 properties, $myFriends and $friendsWithMe for example. You can keep them in sync the same way as described above.

主要区别在于,在数据库级别上,您将只有一条记录表示关系(1,2 或 2,1).这使得查找所有朋友"查询更加复杂,因为您必须检查这两个属性.

The main difference is that on a database level you'll only have one record representing the relationship (either 1,2 or 2,1). This makes "find all friends" queries a bit more complex because you'll have to check both properties.

您当然仍然可以使用数据库中的 2 条记录,方法是确保 addFriend() 将同时更新 $myFriends$friendsWithMe (并保持另一方同步).这会在您的实体中增加一些复杂性,但查询会变得不那么复杂.

You could of course still use 2 records in the database by making sure addFriend() will update both $myFriends and $friendsWithMe (and keep the other side in sync). This will add some complexity in your entities, but queries become a little less complex.

OneToMany/ManyToOne

如果您需要一个用户可以添加朋友的系统,但该朋友必须确认他们确实是朋友,您需要将该确认存储在联接表中.然后,您不再有 ManyToMany 关联,而是类似 User <- OneToMany -> Friendship <- ManyToOne -> User 之类的关联.

If you need a system where a user can add a friend, but that friend has to confirm that they are indeed friends, you'll need to store that confirmation in the join-table. You then no longer have a ManyToMany association, but something like User <- OneToMany -> Friendship <- ManyToOne -> User.

您可以阅读我关于此主题的博文:

You can read my blog-posts on this subject:

  • 学说 2: 如何处理带有额外列的连接表
  • 更多关于 Doctrine 2 中的一对多/多对一关联

这篇关于Doctrine 的多对多自引用和互惠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Doctrine 的多对多自引用和互惠

基础教程推荐