[英]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.