简体   繁体   中英

LEFT JOIN with WHERE on right table, doctrine2 on oneToMany

I found some posts here but it still doesn't work:

I have 2 Entities Story and StoryCompleted:

TA\Minigames\MinigameBundle\Entity\Story:
    type: entity
    table: story
    id:
        id:
            type: integer
            generator: { strategy: AUTO }
    oneToMany:
        completed:
            targetEntity: StoryCompleted
            mappedBy: story
    fields:
        cycle_nr: 
            type: integer

TA\Minigames\MinigameBundle\Entity\StoryCompleted:
    type: entity
    table: story_completed
    id:
        id:
            type: integer
            generator: { strategy: AUTO }
    manyToOne:
        story:
            targetEntity: Story
    fields:
        company_id: 
            type: integer
        completed:
            type: boolean

I would like to get a list of all stories and know which stories are seen by company_id = 1, so I tried a Left Join:

SELECT s FROM MGMinigameBundle:Story s LEFT JOIN s.completed c WHERE s.cycle_nr = 1 AND (c.company_id = $company_id OR c is NULL)

And I wold like to get for a $company_id something like this:

story_id completed
1         1
2         -
3         -

But I get, in each Story, all completed Entities(for all $company_id) and not just one, for a given $company_id and have to Iterate over them to find the one I need. :(

Include "c" in your select statement:

SELECT s, c 
FROM MGMinigameBundle:Story s 
LEFT JOIN s.completed c 
WHERE s.cycle_nr = 1 AND (c.company_id = $company_id OR c is NULL)

This way the StoryCompleted records will be used to "hydrate" the Story object's completed collection based on the company_id. This is the difference between a "regular join" and a "fetch join" in DQL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM