GrailsLearner
GrailsLearner

Reputation: 525

Many to Many relationship in grails

I am trying a many to many relationship example in grails/Gorm. Below is the code what i tried so far.When i am trying to analyze a different scenario i would like to know how Gorm hibernation takes care of it.

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

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

 And in my controller i defined this way in order to add Authors and books.

 def a=new A(name:"ABC")
 def b=new B(title:"Code1")
 a.addToB(b)  
 def a=new A(name:"ABC")
 def b=new B(title:"Code2")
 a.addToB(b)         //It works.

 In the databaselevel it creates

 Table Author        Table Author-Book        Table Book
 id name               id   id                 id    Book
 1  ABC                1     1                 1     Code1
 2  ABC                2     2                 2     Code2

But what i want is the below format:

Table Author        Table Author-Book        Table Book
 id name               id   id                 id    Book
 1  ABC                1     1                 1     Code1
                       1     2                 2     Code2

How can i achieve this when i set name of the author to unique?

Upvotes: 0

Views: 330

Answers (1)

elixir
elixir

Reputation: 1442

Your domain setup is good. You are explicitly creating two authors (with the same name). I would change your code to

def a=new A(name:"ABC")
 def b=new B(title:"Code1")
 a.addToB(b)  
 def a= A.findOrSaveByName("ABC")       // this will attempt to query the db first and only create new record it already doesn't exist
 def b=new B(title:"Code2")
 a.addToB(b)         //It works.

Upvotes: 1

Related Questions