Search code examples
grailsgrails-ormgrails-domain-class

Two way one to many relationship


I have two domain classes one is Game:

class Game {
   String name
   String description
   Double price
   static hasMany = [reviews: Review]
}

and the other one is Review:

class Review {
   String reviewText
   Date reviewDate
   static belongsTo = [game: Game]
}

Both are stripped down versions. I have two objects

r1 = new Review([reviewText: "A game review", reviewDate: new Date()])
g = new Game([name:"Angry Birds", description:"Parabolic physics like game", 20.00])
r1.game=g
r1.save()

After above call is this statement legal?

g.reviews

Will it return a list of all reviews associated with Game? Actually I have an old Grails code which is fetching list of reviews by g.reviews like calls and on Grails 2.4.4, I am getting a null. Was it legal in older versions of Grails? What is the recommended way to fetch reviews associated with a particular game?


Solution

  • save with flush:true if you want to immediately access the db.

    r1.save(flush:true)
    

    then you can say:

    g.reviews