GORM Mapping two attributes of same Class with has

2019-07-16 16:13发布

问题:

I have the following:

class Match{ 
    Team localTeam
    Team visitingTeam
}

class Team{
    static hasMany = [matches: Match]
}

that throws: Error loading plugin manager: Property [matches] in class [class myapp.Team] is a bidirectional one-to-many with two possible properties on the inverse side. Either name one of the properties on other side of the relationship [team] or use the 'mappedBy' static to define the property that the relationship is mapped with. Example: static mappedBy = [matches:'myprop']

So, I use 'mappedBy':

class Team{
    static hasMany = [matches: Match]
    static mappedBy = [matches: localTeam, matches: visitingTeam]
}

but, by doing this, when I get a team from db, matches Set only contains the matches where the team is the visiting team, meaning it only maps matches to the visitingTeam.

If I code de following:

class Team{
    static hasMany = [matches: Match]
    static mappedBy = [matches: localTeam]
}

It only maps matches of the localTeam.

Is there a way to map both matches (when the team is local and when it is the visitor) to the Team?

回答1:

please read the article about GORM Performance Issue first: https://mrpaulwoods.wordpress.com/2011/02/07/implementing-burt-beckwiths-gorm-performance-no-collections

And this might be what you looking for:

class Team {
   String name
   String description

   static constraints = {
    name blank: false, nullable: false
    description blank: true, nullable: true
   }

   static mapping = {
      description type: 'text'
   }

   Set<Match> getHomeMatches() {
    Match.findAllByHomeTeam(this).collect { it.homeTeam } as Set
   }

   Set<Match> getMatches() {
    Match.findAllByTeam(this).collect { it.team } as Set
   }
}


class Match {

   Team homeTeam
   Team team

   static constraints = {
    homeTeam nullable: false
    team nullable: false
   }

   static mapping = {
    id composite: ['homeTeam', 'team']
   }   
} 


回答2:

Try this

class Team {
    static hasMany = [localTeamMatches: Match, visitingMatches: Match]
    static mappedBy = [localTeamMatches: "localTeam", visitingMatches: "visitingTeam"]
}