我想對四個表執行查詢。如何在Doctrine2中爲FROM語句執行子查詢
User
Employments
Company
Votes
User
和Company
經由Employments
相關。 Votes
與其他三個實體沒有直接關係(例如通過PK和FK)。但是Votes
是間接relateable到Company
,因爲它包含列company
,具有相同的字符串值作爲Company
我去直接管理原生SQL查詢中name
列,但在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
聲明中的子查詢不允許嗎?我該如何改變我的查詢才能正確執行?
感謝您的信息,我添加了有關建議使用純SQL的信息。 –