开发者

Can Doctrine2 @OrderBy a calculated field?

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

/** 
 * @OneToMany (targetEntity="Review", mappedBy="product") 
 * @OrderBy ({"voted_up / voted_down" = "DESC"})
 */
protected $reviews;

Is something this possible directly in the model definition or do I need to simply use a sort() o开发者_Python百科n the ArrayCollection when requesting the data?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜