GORM映射与的hasMany同一类的两个属性(GORM Mapping two attribute

2019-09-18 14:19发布

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?

Answer 1:

请先阅读GORM性能问题的文章: https://mrpaulwoods.wordpress.com/2011/02/07/implementing-burt-beckwiths-gorm-performance-no-collections

这可能是你在寻找什么:

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']
   }   
} 


Answer 2:

尝试这个

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


文章来源: GORM Mapping two attributes of same Class with hasMany