[英]Grails 1:m get most relations
I'm relatively new to Grails. 我对Grails比较陌生。 I have the following
我有以下
class House {
Integer number
Integer maxResidents
static belongsTo = [town: Town]
}
class Town {
String name
static hasMany = [houses: House]
}
I want to get five towns with most Houses. 我想获得拥有最多房屋的五个城镇。 I have seen the possibility to create a criteria but I can't deal with it now.
我已经看到了创建标准的可能性,但是我现在无法处理。 Can someone support?
有人可以支持吗? Thank you!
谢谢!
As you have a bidirectional association you can do this with a query on House
: 由于您具有双向关联,因此可以在
House
上执行以下查询:
def result = House.withCriteria {
projections {
groupProperty("town", "town")
rowCount("numHouses")
}
order("numHouses", "desc")
maxResults(5)
}
This would return you a list of results where each result res
has the town as res[0]
and the number of houses as res[1]
. 这将返回一个结果列表,其中每个结果
res
的城镇为res[0]
,房屋数量为res[1]
。 If you'd prefer each result to be a map giving access to res.town
and res.numHouses
then you should add 如果您希望每个结果都为可访问
res.town
和res.numHouses
的地图,则应添加
resultTransformer(AliasToEntityMapResultTransformer.INSTANCE)
after the maxResults
line (along with the appropriate import
at the top of your file). 在
maxResults
行之后(以及文件顶部的相应import
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.