doctrine queryBuilder where IN collection

Matt Welander picture Matt Welander · Nov 9, 2016 · Viewed 8.5k times · Source

On my entity I have an array collection of users

/**
 * @ORM\ManyToMany(targetEntity="\UserBundle\Entity\User", mappedBy="acr_groups")
 */
protected $users;

public function __construct() {
    $this->users = new \Doctrine\Common\Collections\ArrayCollection();
}

In my FormType I want to filter out those groups wherein current user is a member:

    $builder
    ->add('acr_group', EntityType::class, array(
        'label' => 'ATS',
        'class' => 'HazardlogBundle:ACRGroup',
        'query_builder' => function (EntityRepository $er) use ($user) { // 3. use the user variable in the querybilder
                $qb = $er->createQueryBuilder('g');
                $qb->where(':user IN (g.users)');
                $qb->setParameters( array('user' => $user) );
                $qb->orderBy('g.name', 'ASC');
                return $qb;
        },
        'choice_label' => 'name'
    ))

My problem is obviously on this line:

$qb->where(':user IN (g.users)');

How can I use my collection of users as the argument for the IN()?

Answer

Gopal Joshi picture Gopal Joshi · Nov 9, 2016

Try below code

$user = array(12,211,612,84,63,23); // Assuming User Ids whose groups you want to retrive

$builder
->add('acr_group', EntityType::class, array(
    'label' => 'ATS',
    'class' => 'HazardlogBundle:ACRGroup',
    'query_builder' => function (EntityRepository $er) use ($user) { 
            $qb = $er->createQueryBuilder('g');
            $qb->innerJoin('g.users', 'u'); // Inner Join with users
            $qb->where('u.id IN (:user)');
            $qb->setParameters( array('user' => $user) );
            $qb->orderBy('g.name', 'ASC');
            return $qb;
    },
    'choice_label' => 'name'
))

I have tried it in symfony 2.3 with doctrine2. You can use select function with createQueryBuilder() to get specific columns.