Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DQL - Selecting multiple fields, but fetching only one - hiding fields from resultset

Given following DQL query:

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

My resultset will look like following:

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)
...

Is there any DQL functionality so that I will only retrieve the Photo objects and exclude the other selected fields from the resultset? Here is what I'd expect as a result:

array (size=14)
  0 => object(Photo)
  1 => object(Photo)
...
like image 468
httpete Avatar asked Oct 04 '22 14:10

httpete


1 Answers

What you are looking for is computed values in the ORDER clause and the HIDDEN keyword.

In general, you have to do something like following:

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

To "hide" the computed value from the resultset, since Doctrine ORM 2.3, you can use the HIDDEN clause:

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

This is how your DQL would look like:

SELECT 
    p,
    (p.views * 0.1) + (p.likes * 0.9) AS HIDDEN ratingPhoto
FROM
    AppBundle:Photo p
ORDER BY
    ratingPhoto DESC
like image 97
Ocramius Avatar answered Oct 13 '22 10:10

Ocramius