使用 Doctrine 2 querybuilder 在 where 中执行子查询
Doing a subquery inside a where with Doctrine 2 querybuilder
我正在尝试(但没有成功)在 Doctrine2 查询生成器中翻译这个 SQL 查询。我应该如何使用 Querybuilder 将子选择包含在 Where 中?
SQL 我正在尝试使用 querybuilder 实现的查询:
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()
;
}
}
此触发错误信息:
Error: Class 'Message' is not defined.
对于感兴趣的人,我终于找到了解决方案。我是这样查询的(如果有人有其他解决方案我很感兴趣):
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();
}
我正在尝试(但没有成功)在 Doctrine2 查询生成器中翻译这个 SQL 查询。我应该如何使用 Querybuilder 将子选择包含在 Where 中?
SQL 我正在尝试使用 querybuilder 实现的查询:
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()
;
}
}
此触发错误信息:
Error: Class 'Message' is not defined.
对于感兴趣的人,我终于找到了解决方案。我是这样查询的(如果有人有其他解决方案我很感兴趣):
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();
}