Scala光滑按列字符串名称排序

时间:2018-09-05 21:02:28

标签: scala playframework slick

我正试图在光滑的地方实现这种方法:

def paged(page: Long, sorting: String, order: String) = {
    infos.sortBy(_.???).drop((page - 1)*INFOS_PER_PAGE).take(INFOS_PER_PAGE).result
}

但是我不知道要在sortBy中放置什么以及如何将String强制转换为列。 我尝试过这样的简单功能:

class PaymentInfoTable(tag: Tag) extends Table[PaymentInfo](tag, "payment_info") {

def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def date = column[DateTime]("date")
def paymentType = column[String]("payment_type")
def category = column[String]("category")
def subCategory = column[String]("sub_category")
def value = column[BigDecimal]("value")
def comment = column[Option[String]]("comment")
def outsidePaypal = column[Boolean]("outside_paypal")
def outsidePayer = column[Option[String]]("outside_payer")
def sorting(col: String) = {
        if(col == "id") {
            id
        } else if (col == "date") {
            date
        } else if (col == "paymentType") {
            paymentType
        } else if (col == "category") {
            category
        } else if (col == "subCategory") {
            subCategory
        } else if (col == "value") {
            value
        } else if (col == "comment") {
            comment
        } else if (col == "outsidePaypal") {
            outsidePaypal
        } else if (col == "outsidePayer") {
            outsidePayer
        } else {
            id
        }
    }

但是我不能做

sortBy(_.sorting(sorting).asc)

value asc is not a member of slick.lifted.Rep[_1]

我已经导入

import slick.jdbc.MySQLProfile.api._

如何按字符串列名称排序?

1 个答案:

答案 0 :(得分:1)

基本上,您可以做的是添加带有表的字符串/属性的地图

class ColorsTable(tag: Tag) extends Table[Color](tag, "color") with DynamicSortBySupport.ColumnSelector {
  def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
  def name = column[String]("name")
  def * = (id, name) <> ((Color.apply _).tupled, Color.unapply)
  val select = Map(
    "id" -> (this.id),
    "name" -> (this.name)
  )
}

然后您只需要访问该地图

case ((sortColumn, sortOrder), queryToSort) =>
  val sortOrderRep: Rep[_] => Ordered = ColumnOrdered(_, Ordering(sortOrder))
  val sortColumnRep: A => Rep[_] = _.select(sortColumn)
  queryToSort.sortBy(sortColumnRep)(sortOrderRep)

您可以在此找到更多信息,例如但不相同的问题Dynamic order by in scala slick with several columns

如果您想要更简单的方法,只需使用您的列创建一个Order列

if(col == "id") {
  ColumnOrdered(id, Ordering(sortOrder))
}