Mill Hosper
Mill Hosper

Reputation: 49

Grails hasMany with hasOne on the reverse side

I have a simple relationship between two tables as below:

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

class Author {
  String Name
}

I have a requirement that while Book can have many authors, one Author can only have one Book. Authors can exist independent of Books.

With what constraints can I make sure that one Author can have one Book?

Upvotes: 1

Views: 53

Answers (1)

elixir
elixir

Reputation: 1442

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

class Author {
  String Name
  Book book  // this will be the belongTo relationship that you need

  static constraints = {
      book nullable:true
  }
}

Upvotes: 1

Related Questions