用于跟踪用户和游戏的域类

时间:2013-01-25 19:33:37

标签: grails many-to-many gorm

我正在尝试做一些看似简单的事情。我有一个User类,我有一个匹配两个用户的Game类。就这么简单:

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]

我做错了什么?

1 个答案:

答案 0 :(得分:3)

所以这可能是你想要的:

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)
    }
}