2016-07-27 32 views
0

該方案與How to better parse the same table twice with Anorm?上的問題類似,但是不能再使用該問題中描述的解決方案。在Anorm中,可以將多個ColumnAliaser應用於相同查詢

在消息有2個用戶的情況下,我需要用SQL連接解析from_user和to_user。

case class User(id: Long, name: String) 

case class Message(id: Long, body: String, to: User, from: User) 

def userParser(alias: String): RowParser[User] = { 
    get[Long](alias + "_id") ~ get[String](alias + "_name") map { 
     case id~name => User(id, name) 
    } 
} 

val parser: RowParser[Message] = { 
    userParser("from_user") ~ 
    userParser("to_user") ~ 
    get[Long]("messages.id") ~ 
    get[String]("messages.name") map { 
     case from~to~id~body => Message(id, body, to, from) 
    } 
} 

// More alias here possible ? 
val aliaser: ColumnAliaser = ColumnAliaser.withPattern((0 to 2).toSet, "from_user.") 

SQL""" 
SELECT from_user.* , to_user.*, message.* FROM MESSAGE 
JOIN USER from_user on from_user.id = message_from_user_id 
JOIN USER to_user on to_user.id = message.to_user 
""" 
.asTry(parser, aliaser) 
+0

請精確的問題:我想這個問題是不是'ColumnAliaser'實例是否可以重複使用(因爲它顯然不能作爲一成不變的),但有可能ColumnAliaser'應用多個'以相同的查詢 – cchantep

回答

2

如果我是正確的思想要與不同的別名政策,以相同的查詢應用多個ColumnAliaser,是要明白,ColumnAliaser「只是」一個specific implementation of Function[(Int, ColumnName), Option[String]]是很重要的,因此它可以被定義/任何組成Function,並通過其companion object中的工廠功能進行簡化。

import anorm.{ ColumnAliaser, ColumnName } 

val aliaser = new ColumnAliaser { 
    def as1 = ColumnAliaser.withPattern((0 to 2).toSet, "from_user.") 
    def as2 = ColumnAliaser.withPattern((2 to 4).toSet, "to_user.") 

    def apply(column: (Int, ColumnName)): Option[String] = 
    as1(column).orElse(as2(column)) 
} 
相關問題