1

我想对四个表执行查询。

  • User
  • Employments
  • Company
  • Votes

UserCompany通过Employments. Votes与其他三个实体没有直接关系(例如通过 PK 和 FK)。但Votes间接相关Company,因为它包含一个列company,该name列具有与Company

我可以直接在本机 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不允许?如何更改我的查询才能正确执行?

4

1 回答 1

2

from 语句上的选择不由学说 2 处理

关于教义的 jira 有一个已关闭(且不被接受)的功能请求:http: //www.doctrine-project.org/jira/browse/DDC-2793

DQL 是关于查询对象的。在 FROM 子句中支持子选择意味着 DQL 解析器无法再构建结果集映射(因为子查询返回的字段可能不再与对象匹配)。这就是为什么不能支持它的原因(仅在没有水合的情况下运行查询的情况下支持它是不可行的 IMO,因为这意味着查询解析需要依赖于执行模式)。

在您的情况下,最好的解决方案可能是运行 SQL 查询(当您获得标量时,无论如何您都不需要 ORM 水合)

于 2015-01-10T03:55:05.040 回答