我想对四张桌子进行查询。
User
Employments
Company
Votes
User
和Company
通过Employments
相关联。 Votes
与其他三个实体没有直接关系(例如通过PK和FK)。但Votes
与Company
间接相关,因为它包含一列company
,其字符串值与name
我可以直接在本机SQL中管理查询,但是在Doctrine2中我没有看到任何灯光。
本机SQL中的查询查看此
SELECT
c.name AS company,
AVG(vo.vote) AS value,
COUNT(vo.vote) AS votes,
em.employees AS employees
FROM company c
LEFT JOIN employment e ON c.id = e.company_id
LEFT JOIN user u ON e.user_id = u.id
LEFT JOIN (SELECT v.company, v.face
FROM vote v
WHERE v.gender IS NULL
AND v.age IS NULL
AND YEAR( v.timestamp ) = 2013
AND MONTH( v.timestamp ) = 09
AND DAY( v.timestamp ) = 26
) vo ON vo.company = c.name
LEFT JOIN (SELECT employment.company_id, COUNT(employment.user_id) AS employees FROM employment GROUP BY employment.company_id) em ON em.company_id = c.id
WHERE u.id = 1
GROUP BY c.name
如上所述:在纯SQL中这很好用。所以我试着翻译"这进入DQL:
$subqueryVotes = "SELECT v.company, v.vote
FROM vote v
WHERE v.gender IS NULL
AND v.age IS NULL
AND YEAR( v.timestamp ) = :year
AND MONTH( v.timestamp ) = :month
AND DAY( v.timestamp ) = :day";
$subqueryEmployeecount = "SELECT employment.company_id, COUNT(employment.user_id) AS employees FROM employment GROUP BY employment.company_id";
$query = $em->createQuery(
'SELECT
c.name AS company,
AVG(vo.vote) AS value,
COUNT(vo.vote) AS votes,
em.employees AS employees
FROM MyBundle:Company c,
('.$subqueryVotes.') vo,
('.$subqueryEmployeecount.') em
LEFT JOIN c.employments e
LEFT JOIN e.employee u
WHERE vo.gender IS NULL
AND vo.age IS NULL
AND YEAR( vo.timestamp ) = :year
AND MONTH( vo.timestamp ) = :month
AND DAY( vo.timestamp ) = :day
AND u.id = :id
AND vo.company = c.name
AND em.company_id = c.id
GROUP BY c.name'
);
$query->setParameters(array(
'year' => $year,
'month' => $month,
'day' => $day,
'id' => $this->getUser()->getId()
));
$result = $query->getArrayResult();
但现在我明白了:
[Semantical Error] line 0, col 149 near '(
SELECT': Error: Class '(' is not defined.
这是因为我的FROM
子句中的括号中有子选择。是否允许FROM
语句中的子查询?如何更改查询以正确执行?
答案 0 :(得分:2)
from语句中的select不由doctrine 2
处理关于教条jira的封闭(并且未接受)功能请求:http://www.doctrine-project.org/jira/browse/DDC-2793
DQL是关于查询对象的。支持FROM中的子选择 子句意味着DQL解析器无法构建结果集 映射不再(因为子查询返回的字段可能不匹配 对象了。这就是为什么它不能得到支持(支持它 只有在没有水合作用的情况下运行查询的情况是不行的 IMO因为它意味着查询解析需要依赖于 执行模式)。
在您的情况下,最好的解决方案可能是运行SQL查询(因为您正在获得标量,无论如何您都不需要ORM水合作用)