学说的多对多自参照和互惠

2022-01-03 00:00:00 many-to-many php doctrine doctrine-orm

默认情况下,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.

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

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.

单对多/多对一

如果您需要一个用户可以添加朋友的系统,但该朋友必须确认他们确实是朋友,您需要将该确认存储在联接表中.然后,您不再有 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: 如何处理带有额外列的连接表
  • 详细了解教义 2 中的一对多/多对一关联

相关文章