在 Anorm 中是否可以将多个 ColumnAliaser 应用于同一查询

In Anorm is it possible to apply multiple ColumnAliaser to the same query

该场景与 How to better parse the same table twice with Anorm? 中的问题类似,但是无法再使用该问题的描述解决方案。

在消息有 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)

如果我认为您想将具有不同别名策略的多个 ColumnAliaser 应用于同一查询,请务必了解 ColumnAliaser 是 "just" 和 specific implementation of Function[(Int, ColumnName), Option[String]], so it can be defined/composed as any Function, and is simplified by the factory functions in its 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))
}