7.2.1.3 Many-to-many - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari
Version: 3.1.7
7.2.1.3 Many-to-many
Grails supports many-to-many relationships by defining ahasMany
on both sides of the relationship and having a belongsTo
on the owned side of the relationship:class Book { static belongsTo = Author static hasMany = [authors:Author] String title }
class Author { static hasMany = [books:Book] String name }
Author
, takes responsibility for persisting the relationship and is the only side that can cascade saves across.For example this will work and cascade saves:new Author(name:"Stephen King") .addToBooks(new Book(title:"The Stand")) .addToBooks(new Book(title:"The Shining")) .save()
Book
and not the authors!new Book(name:"Groovy in Action") .addToAuthors(new Author(name:"Dierk Koenig")) .addToAuthors(new Author(name:"Guillaume Laforge")) .save()
Grails' Scaffolding feature does not currently support many-to-many relationship and hence you must write the code to manage the relationship yourself