繁体   English   中英

单向一对多关系查询 GORM grails

[英]unidirectional one to many relationship querying GORM grails

Author{
 String name;
 List<Book> books
 static hasMany= [books: Book]
}

Book{
 int number_of_pages;
 String name;
}

我想查询和获取按number_of_pages排序的特定作者的前 10 本书

使用 HQL,您可以执行以下操作:

    def query = "select book from Author author join author.books book where author=:author order by book.number_of_pages"
    def books = Author.executeQuery(query, [author: author], [max: 10])

注意:您应该将number_of_pages重命名为numberOfPages

我建议您通过添加作者作为 Book 的属性,使 Author 对 Book 可见。

这样你可以这样做:

Book.findAll(sort: 'number_of_pages', max: 10) { author.id == myAuthorVariable.id }

虽然,还有更好的方法。 如果你让 Author 实现 equals 方法,你可以写:

Book.findAll(sort: 'number_of_pages', max: 10) { author == myAuthorVariable }    

此外,您可以设置一个“偏移量”,即从 x 寄存器开始给我带来 10 本书。 这对于分页很有用:

Book.findAll(sort: 'number_of_pages', max: 10, offset: 50) { author == myAuthorVariable }    

Author 的 equals 实现可能是:

def boolean equals(author) {
    if (this.is(author)) return true

    if (!author || getClass() != author.class) return false

    return this.name == author.name
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM