是否可以使用 slick return 来自 sql 数据库 table 的自定义列值?

Is it possible to return a custom column value from the sql database table using slick?

有一种情况,当requestType="HR"(来自HTTP PUT请求)时,它应该return所有学生信息但return标题为"EMPLOYEE"

例如,考虑 "student" table 列名称、ID 和标题

 +-------+----+--------------------+
 + name  | id | title              +            
 +-------+----+--------------------+
 | KING  | 10 | SOFTWARE ENGINEER  |
 | BLAKE | 30 | SYSTEMS  ENGINEER  |
 +-------+----+--------------------+

目标:return 所有学生,并覆盖标题="EMPLOYEE"

这是我目前所拥有的

 case class Student(name: String, id: Long, title: String)

 class StudentTable(tag: Tag) extends Table[Student](tag, "student") {
      def name = column[String]("name")
      def id = column[Long]("id")
      def title = column[String]("title")
      override def * = (name, id, title) <> ((Student.tupled, Student.unapply)
 }

 lazy val studentsQuery = TableQuery[StudentTable]

当我尝试映射和更改查询中的 title 值时,它会抱怨 "re-assignment to val"

 val f = studentsQuery.map(p => p.title = "EMPLOYEE).result

complier error: Reassignment to val

方法二: 我尝试将requestType作为函数参数传入StudentTable,这样就可以根据requestType修改title值了。但随后无法定义 studentsQuery,因为它抱怨 "required tag"。

 class StudentTable(tag: Tag)(reqType: String) extends Table[Student](tag, "student") {
      def name = column[String]("name")
      def id = column[Long]("id")
      def title = req.type match {
           case "HR" => "EMPLOYEE"
           case _ => column[String]("title")
      }
      override def * = (name, id, title) <> ((Student.tupled, Student.unapply)
 }

 // Didn't understand how to provide tag 
 lazy val studentsQuery = TableQuery[StudentTable]()("HR")

compilation error: unspecified value parameters: Cons: (Tag) => StudentTable

而不是

val f = studentsQuery.map(p => p.title = "EMPLOYEE).result

你应该有:

val f = studentsQuery.result.map(_.map(p => p.copy(title = "EMPLOYEE")))

我无法通过 Slick 做到这一点,但找到了一种使用 json 序列化来做到这一点的方法。

 import scala.concurrent.Await
 import scala.concurrent.duration._
 import slick.driver.MySQLDriver.api._

 case class Student(name: String, id: Long, title: String)

 class StudentTable(tag: Tag) extends Table[Student](tag, "student") {
      def name = column[String]("name")
      def id = column[Long]("id")
      def title = column[String]("title")
      override def * = (name, id, title) <> ((Student.tupled,Student.unapply)}

 lazy val studentsQuery = TableQuery[StudentTable]


 implicit def StudentDataWrites = new Writes[Student] {
     def writes(student: Student) =
          Json.obj(
              "name"  -> student.name,
              "id"    -> student.id,
              "title" -> "EMPLOYEE"
            )
 }

 def getStudentsInfo() = Action {
    val students= Await.Result(db.run(studentsQuery.size.result), 10.seconds) 
    Ok(Json.obj("students" -> Json.toJson(students)))
}