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

发布于 2024-11-01 00:49:32 字数 732 浏览 5 评论 0原文

我有一个 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 条最新消息。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

违心° 2024-11-08 00:49:32
class Blog {
    ...
    ...
    static hasMany [messages: BlogMessages]
    ...
    ...
}

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

class BlogMessage extends Message {
    Blog blog
}

然后你可以像这样获取...

BlogMessage.list([max:20])
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])
維他命╮ 2024-11-08 00:49:32
def latestMessages = Message.listOrderByDateCreated(max:20, order:"desc")
def latestMessages = Message.listOrderByDateCreated(max:20, order:"desc")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文