Search code examples
symfonydoctrine-ormdoctrine-query

Doctrine 2 Self Join Query


I'm still pretty new to Doctrine and I'm trying to retrieve a suggest list of users to follow.

So basically, given an user A, I need to select all users that are followed by the users that user A follow, excluding users that user A already follow.

How could I do that with Doctrine query builder ?

class User
{

...

/**
 * @ORM\ManyToMany(targetEntity="User", inversedBy="followees")
 * @ORM\JoinTable(name="user_followers",
 *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="follower_id", referencedColumnName="id", onDelete="CASCADE")}
 *      )
 */
private $followers;

/**
 * @ORM\ManyToMany(targetEntity="User", mappedBy="followers")
 */
private $followees;
}

EDIT: According to slaur4 solution, I tried this

    $qb = $this->createQueryBuilder('u');

    $qb->select('suggestions')
    ->join('u.followees', 'followees')
    ->join('followees.followers', 'suggestions')
    ->where('u.id = :id')
    ->andWhere($qb->expr()->notIn('suggestions.id', 'u.followees'))
    ->setParameter('id', $user->getId());

But it gives me the following exception:

QueryException: [Syntax Error] line 0, col 171: Error: Expected Literal, got 'u'

Solution

  • It's a self-referencing query. I would try this :

    QueryBuilder (User Symfony2 repository)

    <?php
    
    //Subquery to exclude user A followees from suggestions
    $notsQb = $this->createQueryBuilder('user')
        ->select('followees_excluded.id')
        ->join('user.followees', 'followees_excluded')
        ->where('user.id = :id');
    
    $qb = $this->createQueryBuilder('suggestions');
    $qb->join('suggestions.followers', 'suggestions_followers')
        ->join('suggestions_followers.followers', 'users')
        ->where('users.id = :id')
        ->andWhere('suggestions.id != :id') //Exclude user A from suggestions
        ->andWhere($qb->expr()->notIn('suggestions.id', $notsQb->getDql()))
        ->setParameter('id', $userA->getId());
    $query = $qb->getQuery();
    $users = $query->getResult(); // array of User