I would like to create a self-referencing entity, but with a description (and possibly other information) about the relationship. An example of this would be friends in a social network application - Person A (entity) can link with Person B (entity), however their relationship could be described as "friend" "brother" "uncle" etc.
From the Doctrine documentation a class can be self referencing with a link table using the following:
<?php
/** @Entity */
class User
{
// ...
/**
* @ManyToMany(targetEntity="User", mappedBy="myFriends")
*/
private $friendsWithMe;
/**
* @ManyToMany(targetEntity="User", inversedBy="friendsWithMe")
* @JoinTable(name="friends",
* joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@JoinColumn(name="friend_user_id", referencedColumnName="id")}
* )
*/
private $myFriends;
public function __construct() {
$this->friendsWithMe = new \Doctrine\Common\Collections\ArrayCollection();
$this->myFriends = new \Doctrine\Common\Collections\ArrayCollection();
}
// ...
}
however it doesn't seem that you can add properties using this method.
The question is, is there a way to handle this in a single class (i.e. User.php) - or would one actually have to make a "link" class - like UserLink.php? I kind of got stuck making a link class when I started on the relations:
class UserLink
{
// ...
/**
* @ORM\Column(type="text", nullable=true)
*/
protected $relationship; // being brother, uncle etc
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="links")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
* @var type
*/
private $user;
}
But I am not sure what happens next...?
Researching on stackoverflow I found similar questions, but more about direct linking.
Doctrine2: Best way to handle many-to-many with extra columns in reference table
Need help understanding Doctrine many to many self referencing code