2

我目前正在使用 Symfony2 框架。我不知道如何通过 Symfony2 中的 Query Builder 加入我的 2 个查询,我只能使用 SQL UNION 查询加入它们。下面是返回正确结果的查询。

SELECT * FROM (SELECT m.id, m.subject, m.date 
FROM message m JOIN message_incoming mi ON m.id = mi.id
WHERE m.recipient_id = 1
AND mi.trash = 1
AND mi.deleted = 0) AS y
UNION 
SELECT * FROM (SELECT m.id, m.subject, m.date 
FROM message m JOIN message_outgoing mo ON m.id = mo.id
WHERE m.originator_id = 1
AND mo.trash = 1
AND mo.sent = 1
AND mo.deleted = 0) AS z
ORDER BY date DESC

我试图在 1 个查询(没有 UNION)中加入此代码以获得正确的结果,但我失败了。

那么如何使用查询生成器来实现这个查询呢?

请指教,谢谢。

4

2 回答 2

2

编写这样的查询而不对 Doctrine2 本身进行太多破解的最佳方法是使用NativeQuery.

native/sqlQueryBuilder使用与 ORM 完全相同的 API。您可以将结果映射到现有实体。

于 2012-06-21T09:55:23.497 回答
0

我不知道在不检查条件的情况下加入 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')

觉得有点傻。

于 2012-06-21T10:11:22.607 回答