tags:

views:

249

answers:

1

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)

+1  A: 

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' ]
}
Stefan
I had another one-to-many relationship, and for your suggestion to work I had to change to "static belongsTo = Person" and add "Person owner" instead. Also added a reverse hasMAny for favoriteRestaurants as well as the mappedBy for class Restaurant. But then it worked
Steve