【问题标题】:Doctrine ORM, ManyToMany - duplicates on lazy fetchDoctrine ORM,ManyToMany - 延迟获取时重复
【发布时间】:2017-02-17 10:54:24
【问题描述】:

Symfony 2.8。使用默认获取模式时返回重复项(为什么?),使用 fetch="EAGER" - 一切正常。

我有以下对象:

/**
 * @ORM\Entity()
 */
class User implements AdvancedUserInterface, \Serializable
{
(...)
    /**
     * @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
     * @ORM\JoinTable(name="user_role",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")}
     * )
     */
    private $role;

    public function addRole(\WerbeoBundle\Entity\Role $role)
    {
        $this->role[] = $role;

        return $this;
    }

    public function removeRole(\WerbeoBundle\Entity\Role $role)
    {
        $this->role->removeElement($role);
    }

    public function getRole()
    {
        return $this->role;
    }

角色:

/**
 * @ORM\Entity()
 */
class Role
{
(...)
    /**
     * @ORM\ManyToMany(targetEntity="User", mappedBy="role")
     */
    private $users;

(... and getters/setters ...)

现在我有下表 user_role:

user_id | role_id
      1 | ADMIN
      1 | EDITOR

当我调用 $user->getRole() 结果是

ADMIN
EDITOR
EDITOR
ADMIN
EDITOR

只有在使用默认获取模式(惰性)时,twig/controller 才会发生这种情况。当 fetch="EAGER" 一切正常。

任何想法我做错了什么? 谢谢

【问题讨论】:

  • 请提供显示您如何获得错误结果的代码(控制器/树枝)。您还可以检查在这两种情况下正在运行哪些查询。你可以在 Symfony 的分析器中检查。
  • 我注意到这可能是一种会话/序列化问题 - 它只影响一个用户对象 - 我已登录。所以问题出在其他地方。

标签: php symfony doctrine-orm orm doctrine


【解决方案1】:

在添加之前必须检查条目是否已经存在

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

public function addRole(\WerbeoBundle\Entity\Role $role)
{
    if(!$this->role->contains($role)){
       $this->role->add($role)
    }

    return $this;
}

【讨论】:

  • 似乎不是解决方案,但我在其他地方有问题。即使在 addRole 中检查角色重复,我也会得到重复的角色,但仅适用于实际登录的用户。所以存储在会话中的用户对象可能存在问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多