我不知道在不检查条件的情况下加入 2 个查询时我有多愚蠢。这是正确的查询:
SELECT m.id, m.subject, m.date
FROM message m
JOIN message_incoming mi ON m.id = mi.id
JOIN message_outgoing mo ON m.id = mo.id
WHERE m.recipient_id = 1
AND mi .trash = 1
AND mi .deleted = 0
OR m.originator_id = 1
AND mo .trash = 1
AND mo .deleted =0
AND mo .sent = 1
ORDER by date DESC
我尝试通过查询生成器实现它:
$queryBuilder = $this->entityManager->getRepository('EzxWebmailBundle:Message')
->createQueryBuilder('m')
->select('m.id','m.subject','m.date')
->join('m.message_outgoing','mo','ON','m.id = mo.id')
->join('m.message_incoming','mi','ON','m.id = mi.id')
->where('m.recipient_id = '.$userId)
->andWhere('mi.trash = 1')
->andWhere('mi.deleted = 0')
->orWhere('m.originator_id = '.$userId)
->andWhere('mo.trash = 1')
->andWhere('mo.deleted = 0')
->andWhere('mo.sent = 1')
->orderBy('m.date','DESC');
$result = $queryBuilder->getQuery()->getResult();
它返回错误的结果多么令人惊讶!因此,我尝试查看使用以下命令生成了什么查询:
var_dump($queryBuilder->getQuery());
而且我真的不知道为什么当我得到这个结果时,学说会产生额外的括号(仔细看看 WHERE 子句):
SELECT m.id, m.subject, m.date FROM message m
INNER JOIN message_outgoing mo ON m.id = mo.id
INNER JOIN message_incoming mi ON m.id = mi.id
WHERE ((m.recipient_id = 1 AND mi.trash = 1 AND mi.deleted = 0) OR m.originator_id = 1) AND mo.trash = 1 AND mo.deleted = 0 AND mo.sent = 1
ORDER BY m.date DESC
因此,如果我添加自己的括号,这一定是正确的:
$queryBuilder = $this->entityManager->getRepository('EzxWebmailBundle:Message')
->createQueryBuilder('m')
->select('m.id','m.subject','m.date')
->join('m.message_outgoing','mo','ON','m.id = mo.id')
->join('m.message_incoming','mi','ON','m.id = mi.id')
->where('(m.recipient_id = '.$userId)
->andWhere('mi.trash = 1')
->andWhere('mi.deleted = 0)')
->orWhere('(m.originator_id = '.$userId)
->andWhere('mo.trash = 1')
->andWhere('mo.deleted = 0')
->andWhere('mo.sent = 1)')
->orderBy('m.date','DESC')
觉得有点傻。