我遇到了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&lt; = 2,我得到一个空结果。我想因为这个周期的事件的绝对,但我问&lt; = 2而不是== 2.任何想法?
答案 0 :(得分:1)
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
此外,当你有条件只是为了加入而不希望它影响来自&#34; main&#34;表,您应该只将它们添加到该连接条件中,如下所示。
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();