在右表上使用WHERE JOFT JOIN,在oneToMany上使用doctrine2

时间:2013-02-21 10:20:54

标签: symfony doctrine-orm left-join

我在这里发现了一些帖子,但它仍然不起作用:

我有2个实体故事和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

我想获得所有故事的列表,并知道company_id = 1看到哪些故事,所以我尝试了左连接:

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)

我想得到这样的$ company_id:

story_id completed
1         1
2         -
3         -

但是,在每个故事中,我得到所有已完成的实体(对于所有$ company_id)而不仅仅是一个,对于给定的$ company_id,并且必须迭代它们以找到我需要的那个。 :(

1 个答案:

答案 0 :(得分:1)

在您的select语句中包含“c”:

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)

这样,StoryCompleted记录将用于根据company_id“水化”Story对象的已完成集合。这是"regular join" and a "fetch join" in DQL

之间的差异