Managing Relationships

As of 0.5 this syntax is deprecated! See next section for migration path.

Since 0.3, Grails provides quite a few methods to ease relationship management. Firstly if you have a one-to-many relationship such as the Author-Book relationship defined below:

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

You can use the dynamic addBook method on author to ease relationship management:

def a = new Author(name:"Stephen King")
             .addBook(new Book(title:"IT"))
             .addBook(new Book(title:"The Stand"))
             .save()

The {{addBook}} method is available at runtime and uses the class name of the {{Book}} to automatically establish the relationship. If it is bidirectional it will also make sure that the {{author}} property of the {{Book}} instance is set.

If you have more than one one-to-many relationship defined for the same class:

class Author {
  String name
  static hasMany = [fiction:Book, nonFiction:Book]
}

You can use the {{add}} method which takes a {{to}} argument which defines which collection to add the book to:

def a = new Author(name:"Stephen King")
             .add(to:"fiction",
                   new Book(title:"IT"))
             .add(to:"nonFiction",
                   new Book(title:"On Writing: A Memoir of the Craft"))
             .save()

Relationship Management for 0.5

Since 0.5, Grails provides quite a few methods to ease relationship management. Firstly if you have a one-to-many relationship such as the Author-Book relationship defined below:

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

You can use the dynamic addToBooks method on author to ease relationship management:

def a = new Author(name:"Stephen King")
             .addToBooks(title:"IT")
             .addToBooks(title:"The Stand")
             .save()

The {{addToBooks}} method is available at runtime and uses the name of the {{books}} collection to automatically establish the relationship. If it is bidirectional it will also make sure that the {{author}} property of the {{Book}} instance is set.

Conversely there is also a {{removeFromBooks}} method for removing a Book from a relationship:

author.removeFromBooks(myBook)

No Comments Yet

Post a Comment