fabien7474
fabien7474

Reputation: 16586

How do hasMany and hasOne work in Grails?

I am having problems defining one-to-one and one-to-many relationships with domain classes. I have the following domain classes

class Team {
    static hasMany = [players: Player]
    static hasOne = [coach: Coach]
}

class Person {
    String name
}

class Player extends Person {
}

class Coach extends Person {
}

So my questions are:

1- Do I need to declare a variable team in Player and in Coach ?

2- Do I need to declare a belongsTo as well?

3- Considering the above classes, is it preferable to use hasOne?

Thank you.

Upvotes: 2

Views: 2952

Answers (2)

Kal
Kal

Reputation: 1717

There is a slight mistake with leebutt's answer.

  1. The cascade is the other way around: if your coach/player has belongsTo set to Team, then a deletion of the team would cascade and delete the coach/player as well.

Upvotes: 2

leebutts
leebutts

Reputation: 4882

  1. Only if you want to be able to easily navigate via player.team and coach.team
  2. Depends on whether or not you want updates/deletes to cascade. I'd think not, as deleting a coach or player should not delete the team or vice versa?
  3. hasOne looks to make sense for the team > coach relation, however it doesn't exist in Grails 1.1.1 or below. It might be in 1.2 (but it's not in the ref guide).

cheers

Lee

Upvotes: 1

Related Questions