Search code examples
controllerentitysymfony4

Symfony 4 get user Entity by id


I'm trying to make a simple Many-To-Many relation, the goal is to Add a friend into the Database.

I'm trying to add a friend using my Controller but i can't find a way to get User entity using the ID.

Following the example in the docs:

    /**
     * @Entity
     */
    class User
    {
        /**
         * @Id
         * @Column(type="integer")
         */
        private $id;
    
        /**
         * @ManyToMany(targetEntity="User")
         * @JoinTable(name="friends",
         *     joinColumns={@JoinColumn(name="user_a_id", referencedColumnName="id")},
         *     inverseJoinColumns={@JoinColumn(name="user_b_id", referencedColumnName="id")}
         * )
         * @var \Doctrine\Common\Collections\ArrayCollection
         */
        private $friends;
    
        /**
         * Constructor.
         */
        public function __construct()
        {
            $this->friends = new \Doctrine\Common\Collections\ArrayCollection();
        }
    
        /**
         * @return array
         */
        public function getFriends()
        {
            return $this->friends->toArray();
        }
    
        /**
         * @param  User $user
         * @return void
         */
        public function addFriend(User $user)
        {
            if (!$this->friends->contains($user)) {
                $this->friends->add($user);
                $user->addFriend($this);
            }
        }
    
        /**
         * @param  User $user
         * @return void
         */
        public function removeFriend(User $user)
        {
            if ($this->friends->contains($user)) {
                $this->friends->removeElement($user);
                $user->removeFriend($this);
            }
        }

And my Controller :

        /**
         * @Route("/addFriends")
         */
        public function addFriends()
        {
            if (isset($_POST['add'])) {
                $id = $_POST['id'];
                $user = $this->getUser();
                $user->addFriend($id);
            }
            return $this->redirectToRoute('friends');
        }

Instead of the $id Symfony wants me to use an instance of entity : Argument 1 passed to App\Entity\User::addFriend() must be an instance of App\Entity\User, string given and I can't find a way to use one.


Solution

  • Try this one:

            if (isset($_POST['add'])) {
                $id = $_POST['id'];
                $user = $this->getUser();
                $friend = $this->getDoctrine()->getRepository(User::class)->find($id);
                $user->addFriend($friend);
            }
    

    Here are details how You should work with doctrine entities