繁体   English   中英

Doctrine DQL从连接返回平面数组

[英]Doctrine DQL returning flat array from join

我在DQL中通过常规LEFT JOIN选择3个实体。 它们通过连接表相关,连接表也有为它们定义的实体以及带注释的关系。 查询执行没有问题,但我的结果作为一个平面数组返回。 我希望有一个数组,其中三个实体作为每个索引的数组元素:

SELECT e1, e2, e3 FROM AppBundle:EntityOne
JOIN AppBundle:JoinEntityOneWithTwo e1_2 WITH e1_2.entity1 = e1.id
JOIN AppBundle:EntityTwo e2 WITH e1_2.entity2 = e2.id
JOIN AppBundle:JoinEntityOneWithThree e1_3 WITH e1_3.entity1 = e1.id
JOIN AppBundle:EntityThree e3 WITH e3.id = e1_3.entity3
WHERE e1.some_field IN ('some','values','in','e1');

当我在查询上调用getResult()时,无论是作为对象还是数组进行保护,我得到一个平坦的结果集:

array(
 /AppBundle/Entity/EntityOne ( ... ),
 /AppBundle/Entity/EntityTwo ( ... ),
 /AppBundle/Entity/EntityThree  ( ... ),
 /AppBundle/Entity/EntityOne ( ... ),
 /AppBundle/Entity/EntityTwo ( ... ),
 /AppBundle/Entity/EntityThree  ( ... ),
 /AppBundle/Entity/EntityTwo ( ... ),
 /AppBundle/Entity/EntityThree  ( ... ),
 /AppBundle/Entity/EntityOne ( ... ),
)

我希望,或者喜欢有一个多维数组:

Array(
[0] => Array(
  [0] /AppBundle/Entity/EntityOne,
  [1] /AppBundle/Entity/EntityTwo,
  [2] /AppBundle/Entity/EntityThree
  ),
[1] => . . . 
)

结果与行无关。 它们也没有任何可预测的顺序,我可以用array_chunk()它们进行array_chunk()

生成的sql运行正常。 DQL返回准确的结果 - 它们不是以我期望的方式制定的。 我正在关注渴望加载连接的Doctrines(难以捉摸)文档:

http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html

这个问题非常相似

Doctrine DQL返回多种类型的实体

但我的选择顺序不同,因为我的连接表是多对多的。 非常感谢!

提出了这个问题的一个变体:

获取Doctrine DQL结果是SQL方式

我很惊讶,学说不支持通过连接表进行急切加载。

这是我能想到的最好的:

//in my entity repository:
public function getFoo($hydrate = true) {
  $sql = "SELECT e1, e2, e3 FROM entity_one
          JOIN entity_one_entity_two e1_2 ON e1_2.entity_one_id = e1.id
          JOIN entity_two e2 ON e1_2.entity_two_id = e2.id
          JOIN entity_one_entity_three e1_3 ON e1_3.entity_one_id = e1.id
          JOIN entity_three e3 ON e3.id = e1_3.entity_three.id
          WHERE e1.some_field IN ('some','values','in','e1')";
  $stmt = $con->prepare($sql);
        $stmt->execute();
  return ($hydrate)
    ? $this->hydrateResponses($stmt->fetchAll(PDO::FETCH_ASSOC))
       : $stmt->fetchAll(PDO::FETCH_ASSOC);
}

public function hyrdateResponses($responses) {
  //call find by ids on repositories from array.
}

这非常有用,因为当您只尝试从一个查询获得结果时,您执行的查询数量为3XN!

在查询中调用getScalarResult()而不是getResult() ,您将获得每个记录合并为一个数组的所有连接表的所有字段:

# Replace this call ...
$query->getQuery()->getResult();
# ... by that call ...
$query->getQuery()->getScalarResult();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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