您不需要任何额外的努力,例如使用 Doctrine Query Builder!
只需将实体类设计为与 UserUser
具有多对多自引用,例如:
* @ORM\Table()
* @ORM\Entity()
*/
class User
{
....
/**
* @var string $name
*
* @ORM\Column(name="name", type="string", unique=true, length=255)
*
*/
private $name;
/**
* @ORM\ManyToMany(targetEntity="User", mappedBy="myFriends")
**/
private $friendsWithMe;
/**
* @ORM\ManyToMany(targetEntity="User", inversedBy="friendsWithMe")
* @ORM\JoinTable(name="friends",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\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();
}
}
然后你可以简单地获取 User 实体并获取所有朋友如下:
$user = $this->getDoctrine()
->getRepository('AcmeUserBundle:User')
->findOneById($anUserId);
$friends = $user->getMyFriends();
$names = array();
foreach($friends as $friend) $names[] = $friend->getName();