2017-09-24 54 views
0

许多好友列表我想要使用多对多的自我引用好友列表。 我跟着this link,它似乎很好。但现在,我应该有我的控制器到什么行动: 1获得所有myFriends /或所有当前用户的所有朋友 2-添加的友情,使用等环节“加为好友”许多人用symfony 3

谢谢你你的时间和答案

回答

0

在你的链接我的朋友是一个学说阵列收集,得到用户的朋友只是重复它,并添加好友只需添加一个朋友到这个收集和保存的实体(与实体经理),也许你需要在集合上添加一个cascade persist来添加一个新用户作为朋友。

你必须添加像getMyFriends,addFriend和removeFriend

<?php 
/** @Entity */ 
class User 
{ 
    // ... 

    /** 
    * Many Users have Many Users. 
    * @ManyToMany(targetEntity="User", mappedBy="myFriends") 
    */ 
    private $friendsWithMe; 

    /** 
    * Many Users have many Users. 
    * @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(); 
    } 

    public function getMyFriends(){ 
     return $this->myFriends; 
    } 

    public function addFriend(User $friend){ 
     $this->myFriends->add($friend); 
    } 

    public function removeFriend(User $friend){ 
     $this->myFriends->removeElement($friend); 
    } 
} 

在控制器中的一些方法你必须实现与

$currentUser= $this->get('security.context')->getToken()->getUser(); 
$myFriends = $currentUser->getMyfriends(); 
$this->render('your-template.html.twig', array(
    'myFriends' => $myFriends, 
)); 

,并在树枝模板的一个操作

<h1>My friends</h1> 
<ul> 
    {% for friend in myFriends %} 
     <li>{{ friend.username }}</li> 
    {% endfor %} 
</ul> 
+0

在我的数据库中,我有一个包含user_id和friend_user_id的新表。但是我的源代码中没有名为“friend”的实体。 – Patron

+0

这是一个自我引用的关系,你没有一个朋友实体它的用户,但现在在你的用户实体,你有一个领域的朋友是一个用户集合 –

+0

它可以吗? –