0
votes

I have an entity called User that has the following:

class User implements UserInterface
{
    /**
     *  @ORM\Id
     *  @ORM\Column(type="string",length=100)
     **/
    protected $id_user;

    /** @ORM\Column(type="string")
     */
    protected $surname;

    /**
     *  @ORM\Column(type="string",length=50)
    */
    protected $name;

  /** 
     * @var ArrayCollection $friends
     * @ORM\ManyToMany(targetEntity="UniDocs\UserBundle\Entity\User")
     * @ORM\JoinTable(name="friends",
     *      joinColumns={@ORM\JoinColumn(name="friend1", referencedColumnName="id_user")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="friend2", referencedColumnName="id_user")}
     *      ) 
    */
    protected $friends; 

.
.
.

/**
     * Get friends
     *
     * @return \Doctrine\Common\Collections\Collection 
     */
    public function getFriends()
    {
        return $this->friends;
    }

.
.
.
}

I need to make a query that gives me the friends of an user which name contain letter 'a' and surname letter 'b' (for example. Those letter are specified on a filter in a web form).

I know I can access all the friends of the registered user using getFriends() method, but... how to filter those friends?

1

1 Answers

0
votes

You cannot do that using getters, you need to write a repository method and use that method in order to fetch exactly what you are looking for.

class FriendRepository extends EntityRepository
{
    public function findByUserAlphabetical(User $user)
    {
        // do query with alphabetical stuff
        return $query = ...
    }
}

Then in your logic:

$friends = $friendRepository->findByUserAlphabetical($user);

$user->setFriends($friends);

Also, you will want to prevent fetching the friends in the original User query, so you can set your annotation fetch to LAZY:

/** 
 * @var ArrayCollection $friends
 * @ORM\ManyToMany(targetEntity="UniDocs\UserBundle\Entity\User", fetch="LAZY")
 * @ORM\JoinTable(name="friends",
 *      joinColumns={@ORM\JoinColumn(name="friend1", referencedColumnName="id_user")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="friend2", referencedColumnName="id_user")}
 *      ) 
 */
 protected $friends;