GORM 将同一类的两个属性映射到 hasMany



>我有以下内容:

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

抛出:加载插件管理器时出错:类 [类 myapp.Team] 是双向一对多,在反侧有两个可能的属性。命名关系 [team] 另一端的属性之一,或使用"mappedBy"静态来定义映射关系的属性。示例:静态映射按 = [匹配:'myprop']

所以,我使用'mappedBy':

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

但是,通过这样做,当我从数据库获得一个团队时,匹配集仅包含团队是访问团队的匹配项,这意味着它仅将匹配项映射到访问团队。

如果我编码 de 以下:

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

它只映射本地球队的比赛。

有没有办法将两场比赛(当球队是本地人时,当它是访客时)映射到球队?

请先阅读有关 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']
   }   
} 

试试这个

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

最新更新