Search code examples
grailshqlgrails-orm

Grails GORM/HQL - retrieve data from association


I have a Blog domain class, which has many messages:

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'
    }
}

Message is used also in other places of the application, so association is unidirectional. How can I get 20 latest blog messages, ordered by creation date? By latest blog messages, I mean 20 latest messages which are associated with ANY blog.


Solution

  • class Blog {
        ...
        ...
        static hasMany [messages: BlogMessages]
        ...
        ...
    }
    
    class Message {
        ...
        // exactly like you have it
        ...
    }
    
    class BlogMessage extends Message {
        Blog blog
    }
    

    Then you can fetch like this...

    BlogMessage.list([max:20])