我有两个mysql表和相应的实体:
Question
--------
id
text
level
Asked
--------
* @ORMManyToOne(targetEntity="QuestionEntity")
* @ORMJoinColumn(name="question", referencedColumnName="id")
question
user
我想查询所有具有特定级别的问题,并且尚未从给定的用户提出问题。我该如何与实体经理查询构建器一起执行此操作?使用MySQL语法,查询将是:
SELECT
*
FROM
Question
WHERE
Question.level = 1
AND Question.id NOT IN( SELECT Asked.question FROM Asked WHERE Asked.user = 23)
我尝试了多种事情,例如Tomasz Madeyski发表了评论,但我仍然遇到500个内部服务器错误。这是我的代码:(我测试了子查询,当它独自一人时很好)
)$em = $this->getDoctrine()->getManager();
$fbUser = $em->getRepository(FbUserEntity::class)->findOneBy(['fbId' => $session->get('fb_user_id')]);
$qb = $em->createQueryBuilder();
$qb2 = $qb;
$questions = $qb->select('q')
->from('MyBundle:QuestionEntity', 'q')
->where('q.level = :level')
->setParameter('level', $level)
->andWhere($qb->expr()->notIn(
'q.id',
$qb2->select('a.question')
->from('LMyBundle:AskedEntity', 'a')
->where('a.user = :userid')
->setParameter('userid', $fbUser->getId())
->getDQL()
))
->getQuery()
->getResult();
尝试这样的东西:
$qb = $em->createQueryBuilder();
$subQuery = $qb->select('a.question')
->from('YourBundle:Asked', 'a')
->andWhere('a.user = 23')
$query = $qb->select('q')
->from('YourBundle:Question', 'q')
->andWhere('q.level = 1')
->andWhere($qb->expr()->notIn('q.id', $subQuery->getDQL())
->getQuery()
->getResult()
这里的关键是 $qb->expr()->notIn()
part
调查我发现的日志,而不是
$qb = $em->createQueryBuilder();
$qb2 = $qb;
我应该为QB2创建一个新的QueryBuilder:
$qb = $em->createQueryBuilder();
$qb2 = $em->createQueryBuilder();
,但这仍然给我一个错误。经过一些实验后,如果执行了子查询,则可以提供类似的格式:
array (size=2)
0 =>
array (size=1)
'question' => int 1
1 =>
array (size=1)
'question' => int 2
所以我经过这样的子查询结果:
$alreadyAsked = [];
foreach($asked as $q){
$alreadyAsked[] = $q['question'];
}
并将已经$的数组传递到这样的主查询,然后起作用:
->andWhere($qb->expr()->notIn('q.id', $alreadyAsked))