简体   繁体   中英

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?

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) 

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