我的团队只有4位玩家。每个玩家的位置都很重要,因此我认为我可以为自己的玩家使用 map ,这是个不错的方法,其键为:pos1
,pos2
,pos3
,pos4
class Team {
Map players = [pos1:null, pos2:null, pos3:null, pos4:null]
static hasMany = [players:Player]
League league
static belongsTo = [club:Club]
static constraints = {
league nullable:true
players nullable:true
}
}
和我的播放器:
class Player{
static belongsTo = [club:Club, team:Team]
String firstname
String lastname
Team team
static constraints = {
team nullable:true
firstname nullable:true
lastname nullable:true
}
public String fullname() {
return firstname + " " + lastname + " - " + team?.id ?: "R"
}
}
我使用
addToPlayers()
方法自动更新播放器,但是尝试以下操作时出现错误:def player = new Player(firstname:"Peter", lastname:"Pan")
def team = new Team()
team.addToPlayers([pos1:player])
Stacktrace在说:
Groovy.lang.MissingMethodException: No signature of method:
org.hibernate.collection.PersistentMap.add() is applicable for argument types:
(at.panda.Player) values: [at.panda.Player : null]
Possible solutions: any(), any(groovy.lang.Closure), any(groovy.lang.Closure), wait(),
wait(long), get(java.lang.Object)
at at.panda.PlayerController$_closure4.doCall(PlayerController.groovy:39)
at at.panda.PlayerController$_closure4.doCall(PlayerController.groovy)
at java.lang.Thread.run(Thread.java:662)
那花了我很多时间,我希望有人能帮助我。如果您有更好的解决方案,则无需坚持使用“ map ”。
最佳答案
就个人而言,我会像这样为您的域建模:
class Team {
//Map players = [pos1:null, pos2:null, pos3:null, pos4:null]
static hasMany = [players:Player]
// The reference to league is now specified below in belongsTo
//League league
static belongsTo = [club:Club,league:League]
static constraints = {
league nullable:true
// must have 4 players
players(size: 4..4)
}
}
class Player{
// Remove the reference to club as this can be retrieved through the Team
static belongsTo = [/*club:Club,*/ team:Team]
String firstname
String lastname
Integer position
// Remove this duplicate reference to team
//Team team
static constraints = {
team nullable:true
firstname nullable:true
lastname nullable:true
// This should ensure that you can't create 2 players with the same position
// in the same team
position(unique:'team')
}
}
该模型将使按位置排列所有玩家的过程变得更加容易,如果您决定更改玩家数量,只需更改约束
players(size: 4..4)
我会考虑向Team添加
addPlayer(Player player)
方法,以正确设置position属性。如果尚未测试以上任何代码,请小心处理。
关于grails - 域使用addTo Map导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8302585/