Mat*_*der 5 doctrine query-builder symfony
在我的实体上,我有一个用户数组集合
/**
* @ORM\ManyToMany(targetEntity="\UserBundle\Entity\User", mappedBy="acr_groups")
*/
protected $users;
public function __construct() {
$this->users = new \Doctrine\Common\Collections\ArrayCollection();
}
Run Code Online (Sandbox Code Playgroud)
在我的FormType中,我想过滤掉其中当前用户是成员的那些组:
$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'
))
Run Code Online (Sandbox Code Playgroud)
我的问题显然在这条线上:
$qb->where(':user IN (g.users)');
Run Code Online (Sandbox Code Playgroud)
如何将用户集合用作IN()的参数?
在尝试您的一些解决方案失败后,我最终扭转了局面。我手动创建了一个我想要的 ID 数组。
可能有一种本地方法可以做到这一点,似乎是一个非常标准的事情......但是这有效。
// 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'
))
Run Code Online (Sandbox Code Playgroud)