Can Doctrine2 @OrderBy a calculated field?

后端 未结 1 760
[愿得一人]
[愿得一人] 2021-01-07 12:45

I want to sort my model\'s associated ArrayCollection with a quotient, like this (I know the following code doesn\'t work):

/** 
 * @OneToMany (         


        
相关标签:
1条回答
  • 2021-01-07 13:19

    With Doctrine 2.1 you can do that directly in the model definition, but not with @OrderBy. You can define DQL snippets at model level, like stated in the 2.1 Beta release notes:

    Named DQL Queries in Metadata: You can add dql queries in the mapping files using @NamedQueries(@NamedQuery(name="foo", query="DQL")) and access them through $em->getRepository()->getNamedQuery().

    As such you can create your DQL query with the ORDER BY keywords, something like:

    SELECT c.id, c.text, (c.voted_up / c.voted_down) AS sortkey FROM Comment c
    ORDER BY sortkey DESC
    

    So, I imagine you add this annotation to the model definition, something like:

    /**
     * @Entity
     * @Table(name="comment")
     * @NamedQueries(@NamedQuery(name="sortedComment", query="SELECT c.id, c.text, (c.voted_up / c.voted_down) AS sortkey FROM Comment c ORDER BY sortkey DESC"))
     */
     class Comment {
         ...
     }
    

    And then on your code call:

    $em->getRepository("Comment")->getNamedQuery("sortedComment");
    

    I didn't test this, but you get the idea.

    0 讨论(0)
提交回复
热议问题