I have an User entity. And those users can be friends together. So I defined a self referencing manyToMany unidirectional association (because there is always reciprocity is friendship, right ?).
a piece of my user entity in YML
manyToMany:
friendList:
targetEntity: User
joinTable:
name: user_friend
joinColumns:
user_id:
referencedColumnName: id
inverseJoinColumns:
friend_id:
referencedColumnName: id
cascade: [persist]
When I call $user->addFriendList($friend), and after a persist and a flush, I have PDOException:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ‘1-2’ for fey ‘PRIMARY’
When I check in the logs, I can see that doctrine is trying to exectue the same insert query twice.
For your information, my addFriendList function
public function addFriendList(User $friend)
{
if (!$this->friendList->contains($friend)) {
$this->friendList[] = $friend;
$friend->addFriendList($this);
}
}
Where am I wrong here ?
I finally found a solution to my issue. However I still don’t know if it’s a Doctrine2 defect or if it works as designed.
I need to persist my user and flush before adding friends.
So my working code is: