2013-03-26 40 views
4

隱藏字段鑑於以下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) 
... 

回答

5

你所尋找的ORDER子句中的計算值和HIDDEN關鍵字。

在一般情況下,你必須這樣做以下:

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

「隱藏」 的computed從結果值,因爲學說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 
+0

該死的我只有教條2.1.5,不過謝謝! – httpete 2013-03-31 01:23:22

+0

@httpete你真的應該考慮升級了,教條2.1不再維護 – Ocramius 2013-03-31 02:11:58

+0

我明白了將!再次感謝,非常乾淨的答案 – httpete 2013-03-31 03:17:13

-3

您可以rewrire您的DQL爲:

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

不能,dql查詢錯誤。 :( 它對你有用嗎? – httpete 2013-03-26 16:00:50

+0

@DmitryKrasun請在以這種方式回答問題之前試用你的代碼,這在EBNF中甚至不支持http://docs.doctrine-project.org/projects/doctrine-orm /en/latest/reference/dql-doctrine-query-language.html#ebnf! – Ocramius 2013-03-29 12:38:40

相關問題