DQL - 选择多个字段,但仅提取一个 - 隐藏结果集中的字段

时间:2013-03-26 11:38:28

标签: doctrine-orm dql

给出以下DQL查询:

SELECT
    p,
    (p.views * 0.1) + (p.likes * 0.9) as ratingPhoto
FROM
    AppBundle:Photo p
ORDER BY
    ratingPhoto DESC

我的结果集如下所示:

array (size=14)
  0 => 
    array (size=2)
      0 => object(Photo)
      'ratingPhoto' => string '1.42' (length=4)
  1 => 
    array (size=2)
      0 => object(Photo)
      'ratingPhoto' => string '1.31' (length=4)
...

是否有任何DQL功能,以便我只检索Photo个对象并从结果集中排除其他选定的字段?这是我期望的结果:

array (size=14)
  0 => object(Photo)
  1 => object(Photo)
...

2 个答案:

答案 0 :(得分:6)

您要查找的是ORDER子句和HIDDEN关键字中的计算值。

通常,您必须执行以下操作:

SELECT
    a,
    b,
    (SOME_COMPUTATION()) AS computed
FROM
    ...
ORDER BY
    computed ASC

要从结果集中“隐藏”computed值,自Doctrine ORM 2.3起,您可以使用HIDDEN子句:

SELECT
    a,
    b,
    (SOME_COMPUTATION()) AS HIDDEN computed
FROM
    ...
ORDER BY
    computed ASC

这就是你的DQL的样子:

SELECT 
    p,
    (p.views * 0.1) + (p.likes * 0.9) AS HIDDEN ratingPhoto
FROM
    AppBundle:Photo p
ORDER BY
    ratingPhoto DESC

答案 1 :(得分:-3)

您可以将SQL重写为:

$dql = "SELECT p
FROM AppBundle:Photo p
ORDER BY ((p.views * 0.1) + (p.likes * 0.9)) DESC";