【问题标题】:Grails GORM/HQL - retrieve data from associationGrails GORM/HQL - 从关联中检索数据
【发布时间】:2011-04-13 11:52:29
【问题描述】:

我有一个博客域类,它有很多消息:

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 条最新消息。

【问题讨论】:

    标签: grails hql grails-orm


    【解决方案1】:
    class Blog {
        ...
        ...
        static hasMany [messages: BlogMessages]
        ...
        ...
    }
    
    class Message {
        ...
        // exactly like you have it
        ...
    }
    
    class BlogMessage extends Message {
        Blog blog
    }
    

    那你就可以这样取了……

    BlogMessage.list([max:20])
    

    【讨论】:

    • 我在想除了继承之外可能还有其他方法来实现我的目标。
    【解决方案2】:
    def latestMessages = Message.listOrderByDateCreated(max:20, order:"desc")
    

    【讨论】:

    • 没关系,但是还有其他类也与 Message 相关联,我只想要那些与博客相关联的消息。
    猜你喜欢
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多