简体   繁体   中英

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

I want to query and fetch top 10 books for a specific author sorted by number_of_pages

Using HQL you can do:

    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])

Note: you should rename number_of_pages to numberOfPages .

I suggest you make Author visible to Book, by adding an author as an attribute for Book.

This way you could do:

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

Although, there's a much better way. If you make Author implement equals method, you can write:

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

Additionally, you can set an 'offset', this is, bring me 10 books starting from the x register. This is usefull for pagination:

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

An implementation of equals for Author could be:

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

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

    return this.name == author.name
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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