[英]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(難以捉摸)文檔:
這個問題非常相似
但我的選擇順序不同,因為我的連接表是多對多的。 非常感謝!
提出了這個問題的一個變體:
我很驚訝,學說不支持通過連接表進行急切加載。
這是我能想到的最好的:
//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.