0

I am working with FOSUserBunde and I want to make a ManytoMany relation on the User entity .

I have seen this post and I have tried to do the same thing .

So this is my code

class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\User", inversedBy="userfriends")
     */
    private $users;

    /**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\User", mappedBy="users")
     */
    private $userfriends;

When I run the update database command I got table with user_user with usertarget and usersource

My problem is that I want to display all usersfriends. Any help please ..

Kzryzstof
  • 7,688
  • 10
  • 61
  • 108
Jessi
  • 3
  • 4

1 Answers1

0

I think you missed some bits in your code. First off, since you make Many-to-Many, that will result in a new table. That is your (usertarget, usersource). Then, you understand that there must be some array somewhere or some way to retrieve information. In SQL, your self-referencing many-to-many, for a user George, showing all his friends, would be like:

SELECT F.Id 
   FROM user U 
   JOIN user_user MtM ON U.Id = MtM.usersource
   JOIN user F ON F.Id = MtM.usertarget
  WHERE U.Name = 'George'

The joins should somehow be replicated in the code. Possibly like that:

* @ORM\JoinTable(name="user_user",
*   joinColumns={
*     @ORM\JoinColumn(name="usersource", 
*                     referencedColumnName="userfriends")
*   },
*   inverseJoinColumns={
*     @ORM\JoinColumn(name="usertarget", referencedColumnName="id")
*   }
* )

The response depends much on what you mean by display all usersfriends. For representations in Symfony, you might need something more complex that just a variable. When there will be data, they need a visible representation, some means to show the results. Check the following links for some ideas:

  • thank you for your answer ! but i really couldn t find a solution ! i ve checked both links but it s not the same case here . because i want a Many_Many on the same entity(User extends BaseUser) i ve tried adding " /** * @var \Doctrine\Common\Collections\Collection|User[]" and this in the constructor "$this->users = new ArrayCollection();" and then i didn t know what else to do to be able to display for each user his userfriends . (ps i m a beginner in symfony) – Jessi Oct 03 '18 at 01:16
  • Many-to-many is implemented with an additional table, with two columns "pointing" to the related entities. In your case, both columns point to the same entity, i.e. table, which makes no difference. The point is that I see no join, i.e. relation, your implementation. I add an extra part in the answer, for that ORM part. – Michael Grivas Oct 03 '18 at 01:27