GORM使用hasMany映射相同类的两个属性 [英] GORM Mapping two attributes of same Class with hasMany

查看:157
本文介绍了GORM使用hasMany映射相同类的两个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

class Match{ 
    Team localTeam
    Team visitingTeam
}

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

会抛出: 加载插件管理器时出错:类[class myapp.Team]中的属性[matches]是双向一对多的,在相反的一侧具有两个可能的属性.可以在关系[team]的另一端命名属性之一,也可以使用'mappedBy'静态属性定义映射关系的属性.示例:静态mappingBy = [matches:'myprop']

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

所以,我使用'mappedBy':

So, I use 'mappedBy':

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

但是,通过这样做,当我从db中获得一个团队时,matchs Set仅包含该团队是客队的比赛,这意味着它仅将比赛映射到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.

如果我编写以下代码:

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

它仅映射localTeam的比赛.

It only maps matches of the localTeam.

是否可以将两个比赛(当团队是本地的和何时是访客)映射到团队?

推荐答案

请先阅读有关GORM性能问题的文章:

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

这篇关于GORM使用hasMany映射相同类的两个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆