doctrine-orm - Doctrine DQL 返回多种类型的实体

标签 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 实体。为什么我也得到订阅和手机的代理?

通过在手机和订阅映射中添加 fetch eager 并从查询中的 SELECT 语句中删除手机和订阅,我只会获得 HandsetSubscription,但我想通过 fetch 连接来完成此操作,如手册中所述(http://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html#joins ).

更新

引用上面发布的链接:

获取地址的连接:

<?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 不需要延迟加载与另一个查询的关联。

最佳答案

非常感谢来自#doctrine irc channel 的 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 

关于doctrine-orm - Doctrine DQL 返回多种类型的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27175873/

相关文章:

php - 是否可以直接从数据库中使用 Doctrine 2 生成模型类?

doctrine - 如何在表格便捷方法中指定HYDRATE_ARRAY?

tree - 学说 2 : Recursively select all self-referenced associated entities (NestedSet)

mysql - 查询时间长

doctrine-orm - 从数据库生成Symfony2固定装置?

php - Symfony 2/存储库 : Error: __clone method called on non-object

php - Mysql时间类型在symfony DateTime类型中返回错误

mysql - 将 MySQL 查询转换为 DQL

symfony1 - Doctrine :多个(whereIn OR whereIn)查询?

php - 交易期间 key '...' 的重复条目 'PRIMARY'