学说queryBuilder IN集合在哪里 [英] doctrine queryBuilder where IN collection

查看:76
本文介绍了学说queryBuilder IN集合在哪里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的实体上,我有一个用户数组集合

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();
}

在我的FormType中,我想过滤掉当前用户是其中成员的那些组:

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)');

如何将我的用户集合用作IN()的参数?

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

推荐答案

在尝试某些解决方案失败后,我终于将事情扭转了一下.我手动创建了所需的ID数组.

I ended up turning thing around a bit after unsuccessfully attempting some of your solutions. I manually created an array of the IDs I wanted.

可能有一种本机的方法,这似乎很标准……但是可行.

There is probably a native way of doing this, seems like a pretty standard thing... this works however.

// 1. to inject user entity into this builder first make a construct function (remember to inject it from controller!)

function __construct($user)
{
    $this->user = $user;
}

/**
 * {@inheritdoc}
 */


public function buildForm(FormBuilderInterface $builder, array $options)
{
    $user = $this->user; // 2. instantiate the variable we created in our construct above

    //create group list array
    $groupList = $this->user->getACRGroups();
    $gla = array(); 
    foreach ($groupList as $g) {
        $gla[] = $g->getId();
    };

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

这篇关于学说queryBuilder IN集合在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆