【问题标题】:Doctrine: Removing entity in self-referencing (many-to-many)学说:在自引用中删除实体(多对多)
【发布时间】:2013-04-30 13:58:50
【问题描述】:

我想请你帮忙删除关联。

我的User 实体:

class User
{
    ...

    /**
     * @ORM\ManyToMany(targetEntity="User", mappedBy="following")
     **/
    private $followers;

    /**
     * @ORM\ManyToMany(targetEntity="User", inversedBy="followers")
     * @ORM\JoinTable(name="friends",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="friend_user_id", referencedColumnName="id")}
     * )
     **/
    private $following;

我有两个动作:

个人资料:关注

// followAction
$entityManager = $this->getDoctrine()->getEntityManager();

$me->addFollowing($targetUser);
$targetUser->addFollower($me);

$entityManager->persist($me);
$entityManager->persist($targetUser);

$entityManager->flush();

个人资料:取消关注

$entityManager = $this->getDoctrine()->getEntityManager();

$me->removeFollowing($targetUser);
$targetUser->removeFollower($me);

$entityManager->persist($me);
$entityManager->persist($targetUser);

$entityManager->flush();

以下过程以正确的方式工作,我看到了适当的记录friends 表。

但是当我试图取消关注用户时,我收到异常:

使用参数 {"1":2,"2":10} 执行“INSERT INTO friends (user_id,friend_user_id) VALUES (?, ?)”时发生异常:

SQLSTATE[23000]:违反完整性约束:1062 键“PRIMARY”的重复条目“2-10”

我做错了什么?我试过persist,没有它,也是一样。也许在关联配置中有些东西?

【问题讨论】:

    标签: doctrine-orm many-to-many associations entities self-join


    【解决方案1】:

    您的第一个错误是 2 个坚持操作,您只需要一个。检查这个:

    // class User
    
    public function switchFollowingUser(User $user)
    {
        if ( $this->following->contains($user) )
            $this->following->removeElement($user) ;
        else
            $this->following->add($user) ;
    }
    

    控制器只是

    $follower->switchFollowingUser($user) ;
    

    如果需要,可以将此方法提取为两个方法,但我更喜欢这种方法,因为它更短。

    第二件事: 你放了吗

    $this->following = new ArrayCollection() ;
    $this->followers = new ArrayCollection() ;
    

    在 __construct() 中?

    试试这是否可行。

    【讨论】:

      猜你喜欢
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      相关资源
      最近更新 更多