本文介绍了如何在查询构建器中编写此查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下(示例)查询:

  SELECT * 
FROM用户u
LEFT JOIN section_user su ON(su.user_id = u.id AND su.section_id = 3)
WHERE section_id为空

我正在使用Symfony2在用户和部分与查询构建器之间的多对多关系中重建它,但是我失败了。



I认为它会是这样的,这证明是错误的:

  $ er-> createQueryBuilder('u')
- > leftJoin('u.sections','s','WITH','s =:section')
- >其中('s为null')
- > setParameter('section',$ section);

帮助非常感谢!

解决方案

我认为这是与相同的情况
但我看到您需要在leftJoin语句中有2个条件,请尝试此
(我假设两个实体中的身份密钥都是 id


$ ('NameBundle:User','u')






$ b - > leftJoin('u.sections','su','ON'
$ qb-> expr() - > andx($ qb-> expr() id','su.user_id'),$ qb-> expr() - > eq('su.id',':section'))

- COUNT(su.id)= 0')
- > groupBy('u.id')
- > setParameter('section',$ section_id);

这将获得所有与ID不相关的用户 $ section_id



编辑:我只是注意到你的示例查询没有任何意义,因为它永远不会返回。但是我想你想要的是没有分配到 $ section_id


的用户

I have the following (exemplary) query:

SELECT *
FROM User u
LEFT JOIN section_user su ON (su.user_id = u.id AND su.section_id = 3)
WHERE section_id is null

I am trying to rebuild it in Symfony2 on a many-to-many relationship between users and sections with query builder but I am failing.

I thought it would look like this, which proves to be wrong:

$er->createQueryBuilder('u')
    ->leftJoin('u.sections', 's', 'WITH', 's = :section')
    ->where('s is null')
    ->setParameter('section', $section);

Help is very appreciated!

解决方案

I think this is the same situation as in hereBut I see you require 2 conditions in leftJoin statement, try this(I am assuming the identity key in both the Entities are id )

$qb->select('u')
 ->from('NameBundle:User','u')
 ->leftJoin('u.sections','su','ON'
    $qb->expr()->andx($qb->expr()->eq('u.id', 'su.user_id'), $qb->expr()->eq('su.id', ':section'))
   )
 ->having('COUNT(su.id) = 0')
 ->groupBy('u.id')
 ->setParameter('section',$section_id);

This will get all the user who are not yet related to section of id $section_id

Edit: I just noticed your example query does not make any sense as it will always return nothing. But I guess what you want are the users that are not assigned to section $section_id

这篇关于如何在查询构建器中编写此查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 06:06