grails:将域类分配给另一个域类

时间:2012-09-27 20:08:46

标签: groovy grails-2.0

我有一个用户被分配到团队的场景 不同的ClientServices分配给不同的团队和
我们需要将这些团队的用户以RoundRobin方式分配给客户服务 我试图按如下方式解决它,以获得一个地图,其中团队名称和ClientServiceInstance列表将被映射,以便我可以对其进行进一步处理

def teamMap = [:]  
clientServicesList.each {clientServiceInstance->  
            if(teamMap[clientServiceInstance.ownerTeam] == null){  
                teamMap.putAt(clientServiceInstance.ownerTeam, new ArrayList().push(clientServiceInstance))  
            }else{  
                def tmpList = teamMap[clientServiceInstance.ownerTeam]  
                tmpList.push(clientServiceInstance)  
                teamMap[clientServiceInstance.ownerTeam] = tmpList  
            }  
        }    

but instead of pushing clientServiceInstance it pushes true.

Any idea?

2 个答案:

答案 0 :(得分:2)

我相信另一个版本是:

def teamMap = clientServicesList.inject( [:].withDefault { [] } ) { map, instance ->
  map[ instance.ownerTeam ] << instance
  map
}

答案 1 :(得分:1)

new ArrayList().push(clientServiceInstance)会返回true,这意味着您将其添加到teamMap中,而不是我认为应该是列表?相反,你可能想要

teamMap.putAt(clientServiceInstance.ownerTeam, [clientServiceInstance])

顺便说一下,你的代码不是很Groovy;)

您可以将其重写为

def teamMap = [:]
clientServicesList.each { clientServiceInstance ->
    if (teamMap[clientServiceInstance.ownerTeam]) {
        teamMap[clientServiceInstance.ownerTeam] << clientServiceInstance
    } else {
        teamMap[clientServiceInstance.ownerTeam] = [clientServiceInstance]
    }
}

虽然我确信有更好的方法可以写出来。