Search code examples
phpsymfonymany-to-manyfosuserbundle

many to many on the same entity symfony


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 ..


Solution

  • 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: