0

I have domain classes => many-to-many and associate them using addTo.

class Books {
    static belongsTo = Author
}

class Author {
    static belongsTo = Book
    static hasMany = [books: Book]
}

Controller:

author.addToBooks(mybook).save()

=> I want to check if mybook is already added to author. Is the a way to check if the book is already added to author (hopefully not using findBy)? Something like

if (author.isAdded(mybook))   

Thanks.

ibaralf
  • 12,218
  • 5
  • 47
  • 69

1 Answers1

6

By default defining as hasMany will use a java.util.Set. Since a Set is a collection that contains no duplicates, this means you can call author.addToBooks() with the same Book and it will not be added more than once - so it isn't necessary to check if a book is present.

However, to check for a Book in the Set, you can use author.books.contains(book)

doelleri
  • 19,232
  • 5
  • 61
  • 65