全部。这是我的代码 -
def searchGames(location: Location, results: List[TournamentResult], roles:
List[Role], player: String, players: List[String], startPl: Int = 6,
endPl:Int = 30, startR: Int = 1, endR: Int = 1000, sy: Int = 2012, ey:
Int = 2017, sm: Int = 0, em: Int = 12, sd: Int = 0, ed: Int = 32) = {
val filtered2 = if (location != Location.SUMRAK) games.filter(_.location === location.name) else games
val filtered3 = if (startPl > 0) filtered2.filter(_.playersSize >= startPl) else filtered2
val filtered4 = if (endPl > 0) filtered3.filter(_.playersSize <= endPl) else filtered3
val filtered5 = if (startR > 0) filtered4.filter(_.rounds >= startR) else filtered4
val filtered6 = if (endR > 0) filtered5.filter(_.rounds <= endR) else filtered5
val filtered7 = if (results != Nil) {
filtered6.filter(a => a.tournamentResult.inSet(results.map(r => r.descr)))
} else filtered6
val filtered8 = filtered7.filter(a => (a.year === sy && a.month >= sm && a.day >= sd) || (a.year === ey && a.month <= em && a.day <= ed) || (a.year > sy && a.year < ey))
val filtered9 = if (player != null && !player.isEmpty) filtered8.filter(_.players like s"%$player%") else filtered8
val filtered14 = filtered9.map(a => (a.gameId, a.location, a.tournamentResult, a.players, a.playersSize, a.rounds, a.year, a.month, a.day))
filtered14.result
}
看起来既不功能也不漂亮。我是Slick的新手,你能建议如何重构吗?光滑的版本是3.0。我认为应该有一些“模式”来提取和简化代码,但我无法弄明白。
答案 0 :(得分:2)
光滑查询的文档提供了一个很好的示例:Queries - Slick 3.0.0 documentation - Sorting and Filtering
简而言之,创建一个Option [criteria]列表(实际上是Rep [Boolean]),收集那些有效的&amp;&amp;&amp;他们在一起。
这样的事情:
val filters = (x:GamesTable) => List(
if (startPl > 0) Some(x.playersSize >= startPl) else None,
if (endPl > 0) Some(x.playersSize <= endPl) else None,
if (startR > 0) Some(x.rounds >= startR) else None,
if (endR > 0) Some(x.rounds <= endR) else None
).collect{case Some(criteria) => criteria}.reduceLeft(_ && _)
games.filter( filters )
制作一个干净的动态查询。