Steve
Steve

Reputation: 203

Multiple associations in grails

I have a grails app with a domain Restaurant and a domain Person.

class Restaurant {
  String name

  static belongsTo = [ owner: Person ]
}

class Person {
  String name

  static hasMany = [ favoriteRestaurants : Restaurant ]
}

My problem is that GORM creates only two tables, Restaurant and Person, where Restaurant has an owner_id. However what I am missing is the join table that links a person's favorite restaurants back to him.

I can understand why GORM does it this way (bidirectional one-to-many), however I can't figure out how to do it the way I want (1x unidirection one-to-many, 1x unidirectional many-to-one). I guess I should use mappedBy but I do not know what to map it to as there is nothing linking it back :-(

Additionally, I was initially considering the following domains:

class Restaurant {
  String name

  static belongsTo = [ owner: Person ]
  static hasMany = [ outstandingCouponOwners : Person ]
}

class Person {
  String name

  static hasMany = [ favoriteRestaurants : Restaurant ]
}

where there is another one-to-many relationship (and again with nothing to map it to on the other end)

Upvotes: 3

Views: 2127

Answers (1)

Stefan Armbruster
Stefan Armbruster

Reputation: 39915

I think, you have to use the 'mappedBy' static map of a domain class. For details look at the bottom of section 5.2.1.2 of the grails reference guide. It might be necessary to introduce additional entries in Person's hasMany: the list of restaurants owned by the person. Try the following (completely untested) code:

class Restaurant {
  String name

  static belongsTo = [ owner: Person ]
  static hasMany = [ outstandingCouponOwners : Person ]
}

class Person {
  String name

  static hasMany = [ favoriteRestaurants : Restaurant, owns: Restaurant, coupons: Restaurant ]
  static mappedby = [ owns: 'owner', coupons: 'outstandingCouponOwners' ]
}

Upvotes: 2

Related Questions