Doctrine DQL返回多种类型的实体

时间:2014-11-27 17:08:29

标签: doctrine-orm dql

我有三个实体:HandsetSubscription,Handset和Subscription。

HandsetSubscription的yaml是:

App\SoBundle\Entity\HandsetSubscription:
type: entity
table: handset_subscription
manyToOne:
    handset:
        targetEntity: Handset
    subscription:
        targetEntity: Subscription                    
id:
    id:
        type: integer
        generator: { strategy: AUTO }
        options: { unsigned: true }
fields:
    amount:
        type: integer
        nullable: false
        options: { default: 0, unsigned: true  }
    discount:
        type: integer
        nullable: false
        options: { default: 0, unsigned: true  }

查询:

SELECT hs,s,h
      FROM  \App\SoBundle\Entity\HandsetSubscription hs                    
      JOIN  \App\SoBundle\Entity\Subscription        s with s.id    = hs.subscription 
                        AND s.mins  = 150 
                        AND s.mb    = 250 
                        AND s.sms   = 150
      JOIN  \App\SoBundle\Entity\Handset             h with h.id    = hs.handset ​

这些是检索到的条目的类名:

App\SoBundle\Entity\HandsetSubscription
Proxies\__CG__\App\SoBundle\Entity\Subscription
Proxies\__CG__\App\SoBundle\Entity\Handset
App\SoBundle\Entity\HandsetSubscription
Proxies\__CG__\App\SoBundle\Entity\Handset
App\SoBundle\Entity\HandsetSubscription
Proxies\__CG__\App\SoBundle\Entity\Handset
…

我希望只能获得HandsetSubscription实体。为什么我也会获得Subscription和Handset的代理?

通过在手机和订阅映射中添加fetch,并从查询中的SELECT语句中删除手机和订阅,我只能获得HandsetSubscription,但我想通过提取连接来完成此操作,如手册中所述({{3 }})。

更新

从上面发布的链接引用:

获取地址的连接:

<?php
$query = $em->createQuery("SELECT u, a FROM User u JOIN u.address a WHERE a.city = 'Berlin'");
$users = $query->getResult();

当Doctrine使用fetch-join对查询进行水合时,它会返回结果数组根级别的FROM子句中的类。在前面的示例中,返回了一个User实例数组,并获取每个用户的地址并将其水合到User#address变量中。如果您访问该地址,则Doctrine不需要延迟加载与另一个查询的关联。

1 个答案:

答案 0 :(得分:4)

非常感谢#doctrine irc频道的veonik解决这个问题。

您应该加入关联,而不是加入实体的完全限定名称。所以查询变为:

SELECT hs,s,h
  FROM  \App\SoBundle\Entity\HandsetSubscription hs                    
  JOIN  hs.subscription s with s.id = hs.subscription 
                    AND s.mins  = 150 
                    AND s.mb    = 250 
                    AND s.sms   = 150
  JOIN  hs.handset h with h.id = hs.handset