Grails: Multiple Relationships Between Two Domain Objects

I am trying to implement two different types of relationships between two domain classes in Grails.

Consider the following; I have two classes of the domain, the class Author and Book, the author has many books.

class Author{           
   String name 
}

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

}

The foregoing describes a very simple relationship between the Author and the Book. But I also want the author to have the concept of a list of favorite books. Ideally, this would be presented as separate for many relationships, describing the same object of the book as a list, and stored as such.

class Author{          
   String name
   static hasMany = [favouriteBooks: Book]

   static mapping = {
        favouriteBooks joinTable: [name: 'favourite_books',
                key: 'author_id']
   }
}

class Book{
   String title
   static belongsTo = [client:Client]

}

, ( ), (favourite_books) . . - , , . , , , , - .

.

+5
3

. , db-reverse-engineer, , . GORM mappedBy, Grails , hasMany . , , :

class Author {

    String name
    static hasMany = [books: Book, favourites: Book]

    // need to disambiguate the multiple hasMany references with the 
    // 'mappedBy' property:
    static mappedBy =   [books: "author",
                        favourites: "authors"]
}

class Book {

    String title
    Author author

    static hasMany = [authors: Author]
    static belongsTo = [Author]
}

+2

, , . Book Author, :

  • , " " Author Book. , , , , .
  • , Author Book " " . --, .

, , , . , " " ( ):

class Author {
    String name
    static hasMany = [favourites: Book]
}

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

, " " , .

static belongsTo = Author

Book, Book , Author . - , , . .

" " :

class Author {
    String name
    static hasMany = [favourites: Book, booksWritten: Book]
}

class Book {
    String title
    static hasMany = [favouritedBy: Author]
    static belongsTo = Author

    Book writtenBy
}

, Author

static mapping = {
    favouriteBooks joinTable: [name: 'favourite_books', key: 'author_id']
}

, favourite_books, author_favourites. - , (, ), .

, , ,

+4

Change domain class Book. Remove the mapping author.

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

Look for the new table FAVORITE_BOOKS once cleanand run-app.

+1
source

All Articles