Doctrine query distinct related entity

爷,独闯天下 提交于 2019-12-09 16:55:25

问题


I'm probably overlooking something very simple and just been staring at it too much, but I can't get this DQL query to work. I get an exception stating:

Cannot select entity through identification variables without choosing at least one root entity alias.

Here's my query. User has a many-to-one relation to Group. Note that this is a unidirectional relation! That may make no sense to you, but it makes sense in our domain logic.

SELECT DISTINCT g
FROM Entity\User u
LEFT JOIN u.group g
WHERE u.active = :active

Can you tell me what I am missing here?


回答1:


Since this is the first Google match when searching for the error message "Cannot select entity through...", I decided to respond despite the topic was posted few months ago.

The trick is to use JOIN ... WITH ... (like JOIN ... ON ... in SQL).

I was having the message with this code:

SELECT ro, COUNT(ro)
FROM FH\MailerBundle\Entity\Recipient r
JOIN r.selectedOption ro
GROUP BY ro.id

I solved the problem by this code:

SELECT ro, COUNT(ro)
FROM FH\MailerBundle\Entity\RecipientOption AS ro
JOIN FH\MailerBundle\Entity\Recipient AS r WITH r.selectedOption = ro
GROUP BY ro.id

I needed to specify full namespaces and classes for both entities.




回答2:


You need to select FROM the root entity alias.. meaning you can't SELECT only from a table you're joining on, as you can in plain sql.. so something like this should do it:

SELECT DISTINCT g
FROM Entity\Group g
INNER JOIN g.user u
WHERE u.active = :active



回答3:


I worked around the problem by doing a subselect:

SELECT g
FROM Entity\Group
WHERE g.id IN (
    SELECT DISTINCT g2.id
    FROM Entity\User u
    LEFT JOIN u.group g2
    WHERE u.active = :active
)



回答4:


You can do this using DQL's new WITH keyword:

SELECT DISTINCT g
FROM Entity\User u
LEFT JOIN Entity\Group g
WITH u in g.users
WHERE u.active = :active



回答5:


I had a similar problem and solved it by multiple from lines like this:

$this->getDoctrine()->createQueryBuilder()
    ->from('ProjectMainBundle:Group', 'g')
    ->from('ProjectMainBundle:User', 'u')
    ->select('distinct(g)')
    ->where('u.group = g')
    ->andWhere('u.active = :active')
    ->....

Hennes




回答6:


I use this

$qb = $this->createQueryBuilder('o')
           ->select('DISTINCT IDENTITY(o.user)')


来源:https://stackoverflow.com/questions/10204700/doctrine-query-distinct-related-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!