使用Doctrine 2 querybuilder在where中进行子查询。

问题描述 投票:0回答:1

我试图在Doctrine2 querybuilder中翻译这个SQL查询(没有成功)。我应该如何在Querybuilder的Where中包含子选择?

我正在尝试用querybuilder实现SQL查询。

SELECT * FROM `message` A 
WHERE A.id =
(SELECT B.id FROM `message` B 
WHERE (A.user_id = B.user_id AND A.receiver_id = B.receiver_id) OR (A.user_id = B.receiver_id AND A.receiver_id = B.user_id)
ORDER BY creationdate DESC 
LIMIT 1)

到目前为止,我在消息库中尝试了类似这样的东西,但我想我离好的方法还很远。

public function getConversations()
    {
      $qb = $this
        ->createQueryBuilder('A')
        ->Where('A.id IN 
            (SELECT B.id FROM Message B 
            WHERE (A.user_id = B.user_id AND A.receiver_id = B.receiver_id) OR (A.user_id = B.receiver_id AND A.receiver_id = B.user_id)
            ORDER BY creationdate DESC
            LIMIT 1')
      ;

      return $qb
        ->getQuery()
        ->getResult()
      ;
    }
}

这触发了错误信息。

错误:'Message'类没有定义。Class 'Message' is not defined.

symfony doctrine-orm query-builder doctrine-query
1个回答
0
投票

对于感兴趣的人,我终于找到了一个解决方案。我做了这样的查询(如果有人有其他的解决方案,我很感兴趣)。

public function getConversations()
{
    $rawSql = "SELECT * FROM `message` A 
                WHERE A.id =
                (SELECT B.id FROM `message` B 
                WHERE (A.user_id = B.user_id AND A.receiver_id = B.receiver_id) OR (A.user_id = B.receiver_id AND A.receiver_id = B.user_id)
                ORDER BY creationdate DESC 
                LIMIT 1)
                ";

    $stmt = $this->getEntityManager()->getConnection()->prepare($rawSql);
    $stmt->execute([]);

    return $stmt->fetchAll();
}
© www.soinside.com 2019 - 2024. All rights reserved.