0

我有以下域类:

class ParentClass {
    String myProperty
    static hasMany = [ childClasses : ChildClass]
}

class ChildClass {
    Date birthday
    static belongsTo = [ parentClass : ParentClass]
}

我需要能够列出按他们最近孩子的生日排序的 ParentClasses。如果我能够params在常规 CRUD 列表页面中使用 used 就更好了。

我知道我可以在控制器中为这个特定的顺序编写一个特定的规则,但我觉得这不是最好的解决方案,我应该根据一个标准使用派生属性或瞬态属性的东西,但不能找不到办法(我对 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是硬编码的。有没有更正确的方法来写这个?

4

2 回答 2

0

如果我理解正确,那么您可以这样做:

def parentClass = new ParentClass(params.id);
// let this be your parentclass 
// you want to have the childs from ordered by birthday

def childListOrderedByBirthday = ChildClass.withCriteria {
    parentClass {
        eq("id", parentClass.id);
    }
    order("birthday", "desc")
}.list()
于 2011-08-20T01:06:31.130 回答
0

crudolf 方法的替代方法是使用动态查找器。它看起来像这样:

def parentClass = new ParentClass(params.id);

def childListOrderedByBirthday =
        ChildClass.findAllByParentClass(parentClass,
                [sort: "birthday", order: "desc"]);

这可能更清楚阅读。

于 2011-08-20T03:54:21.757 回答