可以Doctrine2 @OrderBa计算字段? [英] Can Doctrine2 @OrderBy a calculated field?
问题描述
我想用这个商品(我知道以下代码不起作用)将我的模型的相关联的 ArrayCollection
排序商家:
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;
这可能直接在模型定义中,或者我需要简单地使用sort() ArrayCollection
请求数据?
Is something this possible directly in the model definition or do I need to simply use a sort() on the ArrayCollection
when requesting the data?
推荐答案
使用Doctrine 2.1可以直接在模型定义中执行,但不能使用@OrderBy。您可以在模型级别定义DQL代码段,如 2.1 Beta中所述发行说明:
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:
在元数据中命名DQL查询:您可以使用@NamedQueries(@NamedQuery(name = foo,query =DQL)),并通过$ em-> getRepository() - > getNamedQuery()访问它们。
使用ORDER BY关键字创建您的DQL查询,例如:
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 {
...
}
然后在你的代码调用:
$em->getRepository("Comment")->getNamedQuery("sortedComment");
我没有测试这个,但你得到了这个想法。
I didn't test this, but you get the idea.
这篇关于可以Doctrine2 @OrderBa计算字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!