簡體   English   中英

Symfony2學說DQL Join-在某些情況下沒有結果,但使用SQL會產生結果

[英]Symfony2 doctrine DQL Join - no results for some cases, but results with sql

我用dql遇到了奇怪的問題。

我有兩個帶有外鍵的表連接器:

== Table incident ==
id, cycle_nr, ...
1,  1
2,  3

== Table incident_active ==
id, incident_id, user_id, ...
1,  1,           1
...

我需要顯示一些周期中的活動事件,如果執行mySQL查詢,一切都很好:

SELECT * FROM `incident_active` LEFT JOIN incident ON incident.id = `incident_active`.incident_id WHERE cycle_nr <= 2 and user_id = 1

DQL中的相同查詢也適用,但僅適用於cycle_nr!= 2

SELECT incidentActive, incident 
            FROM AccountingBundle:IncidentActive incidentActive 
            JOIN incidentActive.incident incident
            WHERE incidentActive.company_id = 1 AND incident.cycle_nr <= 2

對於cycle_nr <= 2,我得到一個空結果。 我猜是因為這個周期的事故少之又少,但是我問的是<= 2而不是==2。有什么想法嗎?

DQL中的默認聯接為INNER JOIN。 這些查詢不是等效的。

SELECT * FROM `incident_active`
LEFT JOIN incident ON incident.id = `incident_active`.incident_id
WHERE cycle_nr <= 2 and user_id = 1

此SQL查詢是用DQL這樣編寫的(假設用戶是一個實體)

SELECT incidentActive, incident 
FROM AccountingBundle:IncidentActive incidentActive 
LEFT JOIN incidentActive.incident incident
WHERE incident.cycle_nr <= :cycleNr
  AND incidentActive.user = :userId

另外,當您僅具有聯接條件且不希望其影響“ main”表中的結果時,應僅將它們添加到該聯接條件中,如下所示。

SELECT incidentActive, incident 
FROM AccountingBundle:IncidentActive incidentActive 
LEFT JOIN incidentActive.incident incident WITH incident.cycle_nr <= :cycleNr
WHERE incidentActive.user = :userId

考慮到上面的查詢在$dql ,使用綁定的參數應該看起來像這樣。

$result = $em->createQuery($dql)
    ->setParameter('cycleNr', 2)
    ->setParameter('userId', 1)
    ->getResult();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM