使用提升嵌入时如何在一个案例类字段中组合多列? [英] How to combine multiple columns in one case class field when using lifted embedding?
本文介绍了使用提升嵌入时如何在一个案例类字段中组合多列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们有一个 MySQL 表,其中包含几个布尔列,用于指定用户可能具有的角色.是否可以使用 slick 的提升嵌入来编写一个结合 & 的类型映射器?将这些多列转换为案例类 User 中的一个字段,如下所示?
We have a MySQL table containing several boolean columns which specify the roles a user may have. Is it possible with slick's lifted embedding to write a type mapper which combines & transforms these multiple columns to one field in the case class User like shown below?
case class User(id: Option[Int], nickname: String, role: Seq[Role.Role])
object Users extends Table[(User)]("ask_user") {
def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
def nickname = column[String]("nickname")
def is_editor = column[Boolean]("is_editor")
def is_moderator = column[Boolean]("is_moderator")
def is_administrator = column[Boolean]("is_administrator")
def is_usermoderator = column[Boolean]("is_usermoderator")
def is_usermoderator2 = column[Boolean]("is_usermoderator2")
def is_partner = column[Boolean]("is_partner")
def is_premium_partner = column[Boolean]("is_premium_partner")
def is_corporate_paid = column[Boolean]("is_corporate_paid")
}
推荐答案
您可以使用 * 投影上的 <> 函数为用户对象提供自己的构造函数和提取器函数.像这样:
You can provide your own constructor and extractor functions for User objects to Slick using the <> function on the * projection. Something like this:
class User extends Table[User](...){
...
def * = col1 ~ col2 ~ col3 ~ col4 <> (constructUser, extractUser)
}
def constructUser( col1: T1, col2: T2, col3: T3, col4: T4 )
= User(col1, Roles(col2, col3, col4))
def extractUser( user: User ) = user match{
case User(col1, Roles(col2, col3, col4)) => (col1, col2, col3, col4)
}
object Roles{
def apply( col2: T2, col3: T3, col4: T4 ) : Set[Role] = ...
def unapply( roles: Set[Role] ) : Option[(T2, T3, T4)] = ...
}
另请参阅 http://slick.typesafe.com/doc/1.0.1/lifted-embedding.html#mapped-tables
这篇关于使用提升嵌入时如何在一个案例类字段中组合多列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文