Home » Php » Doctrine – Two links from one table to another

Doctrine – Two links from one table to another

Posted by: admin September 25, 2018 Leave a comment

Questions:

I’m facing a problem with Doctrine. I’m pretty sure that somebody else has already got the same problem as me but I can’t find it anywhere on StackOverFlow…

I have two objects: User and FriendLink.
The linked tables (sorry for this ugly paint!)

FriendLink is supposed to represent the friendship between two users. As a friendship is reciprocal, there is two lines for each friendship.

For example: a user with id=1 is friend with a user whose id=2. In the table friend_links there will be two lines:

  • user_id = 1 and friend_id = 2
  • user_id = 2 and friend_id = 1.

The two lines are linked to the user. I mean that if the user with the id=1 is deleted, the two lines must be deleted also.

I tried with a OneToMany() but I’m pretty sure it’s not the right way because I will not be able to execute the following code:

// friendship in one way
$user = new User();
$user->setId(1)
$friend_link = new FriendLink();
$friend_link->setFriendId(2)
$friend_link->setAuthorization(true);
$friend_link->setCreationDatetime(new Datetime());

$user->addFriendLink($friend_link)
$entityManager->persist($user);
$entityManager->flush();

// friendship in the other way
$user = new User();
$user->setId(1)
$friend_link = new FriendLink();
$friend_link->setUserId(2)
$friend_link->setAuthorization(true);
$friend_link->setCreationDatetime(new Datetime());

$user->addFriendLink($friend_link)
$entityManager->persist($user);
$entityManager->flush();

With OneToMany() I can only execute this following code:

$user = new User();
$friend_link = new FriendLink();
$friend_link->setAuthorization(true);
$friend_link->setCreationDatetime(new Datetime());

$user->addFriendLink($friend_link)
$entityManager->persist($user);
$entityManager->flush();

I dont even know if my way of proceeding if good.

How can I deal with ?
Thanks in advance.

Answers: