Scala slick 按列字符串名称排序

Scala slick sort by column string name

我正尝试在 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._

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

基本上你可以做的是添加一个地图 string/property of the table

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)

您可以在此找到更多信息,例如但不相同的问题

如果您想要更简单的东西,只需使用您的列创建一个订单列

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