Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

doctrine queryBuilder where IN collection

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()?

like image 636
Matt Welander Avatar asked Nov 09 '16 07:11

Matt Welander


1 Answers

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.

like image 118
Gopal Joshi Avatar answered Nov 01 '22 12:11

Gopal Joshi