2013-09-26 60 views
1

我想對四個表執行查詢。如何在Doctrine2中爲FROM語句執行子查詢

  • User
  • Employments
  • Company
  • Votes

UserCompany經由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聲明中的子查詢不允許嗎?我該如何改變我的查詢才能正確執行?

回答

2

選擇在從聲明中不被教條2

處理上有學說的JIRA封閉(不接受)功能要求:http://www.doctrine-project.org/jira/browse/DDC-2793

DQL是有關查詢的對象。子句FROM 子句中的支持子查詢意味着DQL解析器不能再構建結果集 映射(因爲子查詢返回的字段可能不再與 對象匹配)。這就是爲什麼它不能被支持的原因(只支持它 只適用於你運行查詢而沒有水化的情況,因爲這將意味着查詢解析需要依賴於 執行模式),因此是不可行的 IMO。

在你的情況,最好的解決辦法可能是運行SQL查詢,而不是(因爲你得到一個標量,你不需要ORM水化反正)

+0

感謝您的信息,我添加了有關建議使用純SQL的信息。 –

相關問題