在我的实体上,我有一个用户数组集合
/**
* @ORM\ManyToMany(targetEntity="\UserBundle\Entity\User", mappedBy="acr_groups")
*/
protected $users;
public function __construct() {
$this->users = new \Doctrine\Common\Collections\ArrayCollection();
}
在我的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'
))
我的问题显然在这一行:
$qb->where(':user IN (g.users)');
如何使用我的用户集合作为IN()的参数?
答案 0 :(得分:3)
尝试以下代码
symfony 2.3
我已使用doctrine2
在select
中尝试过。您可以使用createQueryBuilder()
功能与from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime
def tick():
text = 'Tick! The time is: %s' % datetime.now()
saveLog(text)
if __name__ == '__main__':
scheduler = BlockingScheduler()
scheduler.add_job(tick, 'cron', hour=9)
scheduler.start()
获取特定列。
答案 1 :(得分:0)
$q = $this->createQueryBuilder('v')
->select('v')
->andWhere('v.workingHours IN (:workingHours)')
->setParameter('workingHours', $workingHours);
来自:Doctrine 2 WHERE IN clause using a collection of entities
或根据学说文档:http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html#the-expr-class 要在带有doctrine的查询生成器中插入IN条件,可以使用expr()
$qb->add('select', new Expr\Select(array('u')))
->add('from', new Expr\From('User', 'u'))
->add('where', $qb->expr()->orX(
$qb->expr()->eq('u.id', '?1'),
$qb->expr()->like('u.nickname', '?2')
))
->add('orderBy', new Expr\OrderBy('u.name', 'ASC'));
IN的语法:
$qb->expr()->in('u.id', array(1, 2, 3))
另外,请确保不使用与$qb->expr()->in('value', array('stringvalue'))
类似的内容,因为这会导致Doctrine抛出异常。相反,请使用$qb->expr()->in('value', array('?1'))
并将参数绑定到?1
答案 2 :(得分:-1)
在尝试了一些解决方案失败后,我最终扭转了局面。我手动创建了一个我想要的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'
))