我有以下与用户和地址关联的模型:
User
- id
- email
- password
Address
- id
- street
- zip_code
- city
- user_id
One user has [0:n] Address :
users (id, email, password)
======================================
| 1 | "someone1@example.org" | "..." |
| 2 | "someone2@example.org" | "..." |
| 3 | "someone3@example.org" | "..." |
| 4 | "someone4@example.org" | "..." |
| 5 | "someone5@example.org" | "..." |
======================================
addresses (id, street, zip_code, city, user_id)
===================================================
| 1 | "Somewhere" | "00001" | "City 1" | 1 |
| 2 | "Somewhere else" | "00002" | "City 2" | 1 |
| 3 | "Somewhere" | "00003" | "City 3" | 1 |
| 4 | "Somewhere else" | "00001" | "City 1" | 2 |
| 5 | "Somewhere" | "00002" | "City 2" | 2 |
| 6 | "Somewhere else" | "00003" | "City 3" | 2 |
| 7 | "Somewhere" | "00001" | "City 1" | 3 |
| 8 | "Somewhere else" | "00003" | "City 3" | 3 |
| 9 | "Somewhere" | "00002" | "City 2" | 4 |
| 10 | "Somewhere else" | "00003" | "City 3" | 4 |
===================================================
我想选择在“城市1”中有一个地址的用户:addresses.id in(1,4,7),出于某种原因,我需要包括正好有0个地址的用户。
==>[1(地址1)、2(地址4)、3(地址7)和5(无地址)],但不是用户4(有地址但无匹配)。
以下是我试过的几个问题…
内部连接
=>[1(地址1),2(地址4),3(地址7)](但不是用户5)
$queryBuilder = $this->em->createQueryBuilder('u');
$queryBuilder
->innerJoin('u.addresses', 'a', \Doctrine\ORM\Query\Expr\Join::WITH, $queryBuilder->expr()->in('a.id', ':ids'))
->setParameter('ids', [1, 4, 7])
;
左连接
=>[1(地址1,2,3),2(地址4,5,6),3(地址7,8),4(地址9,10),5(无地址)]
$queryBuilder = $this->em->createQueryBuilder('u');
$queryBuilder
->leftJoin('u.addresses', 'a', \Doctrine\ORM\Query\Expr\Join::WITH, $queryBuilder->expr()->in('a.id', ':ids'))
->setParameter('ids', [1, 4, 7])
;
左连接+
addSelect('a')
=>[1(地址1),2(地址4),3(地址7),4(无地址),5(无地址)]
$queryBuilder = $this->em->createQueryBuilder('u');
$queryBuilder
->leftJoin('u.addresses', 'a', \Doctrine\ORM\Query\Expr\Join::WITH, $queryBuilder->expr()->in('a.id', ':ids'))
->addSelect('a')
->setParameter('ids', [1, 4, 7])
;
内部联接+大小()条件
=>[1(地址1),2(地址4),3(地址7)](但不是用户5)
$queryBuilder = $this->em->createQueryBuilder('u');
$queryBuilder
->innerJoin('u.addresses', 'a', \Doctrine\ORM\Query\Expr\Join::WITH, $queryBuilder->expr()->in('a.id', ':ids'))
->orWhere($queryBuilder->expr()->eq('SIZE(u.addresses)', 0))
->setParameter('ids', [1, 4, 7])
;
一个查询就可以做到吗?如果可以,怎么做?
最佳答案
如果要选择没有任何地址的用户,则需要执行LEFT JOIN
并测试检索到的值是否NULL
(如所述here)。因此,如果希望将这两个条件结合起来,则需要像这样构建查询:
$qb = $this->createQueryBuilder('u')
->leftJoin('u.addresses', 'a')
->addSelect('a') // If you wish to retrieve the address at the same time
->where('a.id IS NULL OR a.id IN (:ids)')
->setParameter('ids', $ids);
考虑到您的用例,您甚至可以编写这样的where条件:
'a.id IS NULL OR a.city = :cityName'
以按城市名称筛选,并避免事先检索addresses
条目的id。使用上述查询生成器,Doctrine生成如下所示的SQL查询:
SELECT ... FROM users u0_
LEFT JOIN addresses a1_ ON u0_.id = a1_.user_id
WHERE a1_.id IS NULL OR a1_.id IN (1, 4, 7)