Search code examples
grailsgrails-orm

Grails, gorm. Find child by parent and parent by child


For example, I've parent class Author:

class Author {    
    String name
    static hasMany = [
         fiction: Book, 
         nonFiction: Book
    ]
}

and a child class Book:

class Book {    
    String title
    static belongsTo = [author: Author]
}

I've done some records to Author using:

def fictBook = new Book(title: "IT")
def nonFictBook = new Book(title: "On Writing: A Memoir of the Craft")
def a = new Author(name: "Stephen King")
             .addToFiction(fictBook)
             .addToNonFiction(nonFictBook)
             .save()

How can I found child-class record by parent and parent-class record by child?


Solution

  • In my opinion, this is not the best way to model your data. I would do it like this.

    class Author {    
      String name
      static hasMany = [books: Book]
    }
    
    class Book {
      String title
      BookTypes bookType
      static belongsTo = [author: Author]
    }
    
    enum BookTypes {
      FICTION,
      NON_FICTION
    }
    

    Then, you can do lookups like

    def author = Author.get(1)
    def nonFictionByAuthor = Book.findAllByAuthorAndBookType(author, BookTypes.NON_FICTION)
    

    You could also just do something like this...

    def author = Author.get(1)
    def fictionBooks = author.books.findAll { it.bookType == BookTypes.FICTION }
    

    And then inversely:

    def fictionBook = Book.findByTitleAndBookType('Title001', BookTypes.FICTION)