【问题标题】:Domain classes to track Users and Games跟踪用户和游戏的域类
【发布时间】:2013-01-25 19:33:37
【问题描述】:

我正在尝试做一些看起来很简单的事情。我有一个用户类,我有一个匹配两个用户的游戏类。就这么简单:

class User {
    String username
    static hasMany = [games:Game]
}

class Game {
    User player1
    User player2
}

当我运行这个时,我得到了

Caused by GrailsDomainException: Property [games] in class [class User] 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 [user] or use the 'mappedBy' static to define the property that the relationship is mapped with. Example: static mappedBy = [games:'myprop']

所以我做了一些挖掘,找到了mappedBy并将我的代码更改为:

class User {
    String username
    static hasMany = [games:Game]
    static mappedBy = [games:'gid']
}

class Game {
    User player1
    User player2
    static mapping = {
        id generator:'identity', name:'gid'
    }
}

现在我明白了

Non-existent mapping property [gid] specified for property [games] in class [class User]

我做错了什么?

【问题讨论】:

  • 我会放弃你的开始,将关系定义为简单的多对多,并控制其他地方每场比赛只有 2 名玩家的商业逻辑。
  • 所以你的意思是保持域相对简单,只需说一个Game hasMany Users,然后确保它是两个不同用户控制器?

标签: grails many-to-many grails-orm


【解决方案1】:

所以这可能就是你想要的:

class User {

    static mappedBy = [player1Games: 'player1', player2Games: 'player2']

    static hasMany = [player1Games: Game, player2Games: Game]

    static belongsTo = Game
}

class Game {
    User player1
    User player2
}

编辑新规则:

class User {
    static hasMany = [ games: Game ]
    static belongsTo = Game
}

class Game {
    static hasMany = [ players: User ]
    static constraints = {
        players(maxSize: 2)
    }
}

【讨论】:

  • 请注意,这样做的唯一原因是您需要/想要从用户对象获取游戏。
  • 这行得通,谢谢。但是有一件事仍然不适合我的情况。我创建了 player1 和 player2 变量,因为我看不到绕过它的方法。 (为我的 OP 中的误导性道歉。)我真的不想区分它们。游戏中的两个玩家之间没有真正的区别。 Game 是否有可能拥有一个用户数组(大小为 2 是理想的)?并且对于用户有很多游戏,而不是 player1Games 和 player2Games?我想查找用户所属的所有游戏,而玩家 1 或玩家 2 无关紧要。
  • 太完美了。话虽如此,是否有一个简单的解决方法可以让脚手架在这里工作?
猜你喜欢
  • 2017-08-10
  • 1970-01-01
  • 2014-06-11
  • 2013-12-08
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-11
相关资源
最近更新 更多