我可以使用“开"吗?DQL 中的关键字还是我需要使用 Native Query? [英] Can I use "ON" keyword in DQL or do I need to use Native Query?
问题描述
我在 Post 和 PostVote 之间有一个 oneToMany 关系.我希望能够检索帖子以及特定用户如何对其进行投票.在 DQL 中,我想检索 Post 和相关的 PostVote 实体,但只有一个 user_id 是例如 5.
I have a oneToMany relationship between Post and PostVote. I would like to be able to retrieve a Post and how a specific user voted on it. In DQL I would like to retrieve Post and related PostVote entity, but only one where user_id is for example 5.
我似乎无法像这样使用 ON sql 关键字:
I don't seem to be able to use ON sql keyword like this:
->createQuery('SELECT p, pv FROM Post p LEFT JOIN p.postvotes ON pv.user = :userid WHERE p.id = :postid')
如果我使用 WHERE 来过滤结果,就会产生问题并且不会显示结果,除非至少存在一个 postvote 对象:
And if I use WHERE to filter out results, it create a problem and does not display a result unless at least one postvote object exists:
->createQuery('SELECT p, pv FROM Post p LEFT JOIN p.postvotes WHERE p.id = :postid' AND pv.user = :userid)
本机查询是我实现这一目标的唯一方法吗?
Is Native Query the only way I can achieve this?
推荐答案
你必须在 DQL 中使用 WITH 关键字来完成这个:
You have to use the WITH keyword in DQL to accomplish this:
SELECT p, pv FROM Post p LEFT JOIN p.postvotes WITH pv.user = :userid WHERE p.id = :postid
这篇关于我可以使用“开"吗?DQL 中的关键字还是我需要使用 Native Query?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!