Many To Many friendlist with symfony 3

342 views Asked by At

I want to make a friendlist using ManyToMany self-referencing. I followed this link and it seemms to be good. But Now, what Action should I have in my controller to : 1- get All myFriends / or all all friend of current user 2- add a firend, using a link such as "Add friend"

thank you for your time and answers

1

There are 1 answers

6
François LEPORCQ On

in your link my friends is a doctrine array collection, to get the friends of a user just iterate on it and to add a friend just add a friend onto this collection and save the entity (with the entity manager), maybe you ll need to add a cascade persist on the collection to add a new user as friend.

you have to add some methods like getMyFriends, addFriend and 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);
    }
}

in your controller you have to implement an action with

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

and in your twig template

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