如何基于 Grails 上的子集合属性创建域瞬态属性?
我有以下域类:
class ParentClass {
String myProperty
static hasMany = [ childClasses : ChildClass]
}
class ChildClass {
Date birthday
static belongsTo = [ parentClass : ParentClass]
}
我需要能够列出按最近孩子的出生日期排序的 ParentClass。如果我能够使用常规 CRUD 列表页面中使用的 params
那就最好了。
我知道我可以在控制器中为这个特定的顺序编写一个特定的规则,但我觉得这不是最好的解决方案,我应该根据标准使用派生属性或瞬态属性的一些东西,但不能找不到方法来做到这一点(我对 Grails 和 Hibernate 有点陌生)。
任何指示将不胜感激。
编辑:我设法做到了这一点:
static mapping = {
mostRecentBirthday formula: '(
SELECT c.data
FROM ChildClass c
WHERE c.parent_class_id=id
ORDER BY c.birthday DESC LIMIT 1
)'
}
这个解决方案的唯一问题是 parent_class_id
是硬编码在那里的。有更正确的写法吗?
I have the following domain classes:
class ParentClass {
String myProperty
static hasMany = [ childClasses : ChildClass]
}
class ChildClass {
Date birthday
static belongsTo = [ parentClass : ParentClass]
}
I need to be able to list ParentClasses ordered by the birthdate of their most recent child. It would be best if I were able to use the params
used in the regular CRUD list pages.
I know I could write a specific rule in the controller for this specific ordering, but I feel like it is not the best solution and that I should use something along the lines of a derived property or a transient property based on a criteria, but couldn't find a way to do it (I'm kind of new to Grails and Hibernate).
Any pointers would be appreciated.
Edit: I managed to do this:
static mapping = {
mostRecentBirthday formula: '(
SELECT c.data
FROM ChildClass c
WHERE c.parent_class_id=id
ORDER BY c.birthday DESC LIMIT 1
)'
}
The only problem I have with this solution is that parent_class_id
is hard coded in there. Is there a more correct way to write this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我理解正确的话,你可以这样做:
If I understand correctly, then you can do it like this:
crudolf 方法的替代方法是使用 动态查找器。它看起来像这样:
这可能更容易阅读。
An alternate to crudolf's approach is to use a dynamic finder. It would look like this:
This may be cleaner to read.