Grails GORM / HQL - 从关联中检索数据

时间:2011-04-13 11:52:29

标签: grails hql gorm

我有一个Blog域类,其中包含许多消息:

class Blog {

    String description

    static hasMany = [messages : Message]
    static belongsTo = [owner : User]

    static constraints = {
        description blank: true, nullable: true
    }
}

class Message {

    String content
    String title
    User author

    Date dateCreated
    Date lastUpdated

    static hasMany = [comments : Comment]

    static constraints = {
        content blank: false
        author nullable: false
        title nullable: false, blank: false
    }

    static mapping = {
        content type: "text"
        sort dateCreated: 'desc'
    }
}

消息也在应用程序的其他位置使用,因此关联是单向的。如何根据创建日期排列20条最新博客消息?根据最新的博客消息,我的意思是与任何博客相关的20条最新消息。

2 个答案:

答案 0 :(得分:1)

class Blog {
    ...
    ...
    static hasMany [messages: BlogMessages]
    ...
    ...
}

class Message {
    ...
    // exactly like you have it
    ...
}

class BlogMessage extends Message {
    Blog blog
}

然后你就可以这样取......

BlogMessage.list([max:20])

答案 1 :(得分:0)

def latestMessages = Message.listOrderByDateCreated(max:20, order:"desc")