3

I'm new to Grails and GORM and I try to implement a "One to Many" relationship. I tried the example in the doc :

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

Here are the tables that are generated :

AUTHOR
- Id (PK)
- Name

BOOK
- Id (PK)
- Title

AUTHOR_BOOK
- Author_Books_Id
- Book_Id

I was expecting something more like :

AUTHOR
- Id (PK)
- Name

BOOK
- Author_Id (PK)
- Book_Index (PK)
- Title

Is there a way to achieve this (get rid of the join table) ?

Yann
  • 303
  • 1
  • 5
  • 11

3 Answers3

18

You should declare that Book belongs to Author. With belongsTo you declare that there is foreign key in a Book table that keeps reference to Author's id column. Like this:

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

class Author {
    static hasMany = [books: Book]
    String name 
}
Tomasz Kalkosiński
  • 3,673
  • 1
  • 19
  • 25
0

Just do it the other way around.

A Book has an Author.

class Book {
    String title
    Author author
}

class Author {
    String name 
}
moskiteau
  • 1,104
  • 11
  • 19
0

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

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

vsharma
  • 299
  • 3
  • 3