开发者

How to create a domain transient property for based on a child collection's property on Grails?

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?


If I understand correctly, then you can do it like this:

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()


An alternate to crudolf's approach is to use a dynamic finder. It would look like this:

def parentClass = new ParentClass(params.id);

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

This may be cleaner to read.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜