如何连接两个表并将结果映射到Slick中的case类 [英] How to join two tables and map the result to a case class in slick
问题描述
我正在使用scala play 2框架在一个项目中工作,在该框架中,我使用slick作为FRM和postgres数据库.
I am working in a project with scala play 2 framework where i am using slick as FRM and postgres database.
在我的项目中,客户是一个实体.因此,我还创建了一个客户表以及客户案例类和对象.另一个实体是帐户.因此,我还创建了一个帐户表以及帐户案例类和对象.代码如下所示
In my project customer is an entity. So i create a customer table and customer case class and object also. Another entity is account. So i create a account table and account case class and object also. The code is given bellow
case class Customer(id: Option[Int],
status: String,
balance: Double,
payable: Double,
created: Option[Instant],
updated: Option[Instant]) extends GenericEntity {
def this(status: String,
balance: Double,
payable: Double) = this(None, status, balance, payable, None, None)
}
class CustomerTable(tag: Tag) extends GenericTable[Customer](tag, "customer"){
override def id = column[Option[Int]]("id")
def status = column[String]("status")
def balance = column[Double]("balance")
def payable = column[Double]("payable")
def account = foreignKey("fk_customer_account", id, Accounts.table)(_.id, onUpdate = ForeignKeyAction.Restrict, onDelete = ForeignKeyAction.Cascade)
def * = (id, status, balance, payable, created, updated) <> ((Customer.apply _).tupled, Customer.unapply)
}
object Customers extends GenericService[Customer, CustomerTable] {
override val table = TableQuery[CustomerTable]
val accountTable = TableQuery[AccountTable]
override def copyEntityFields(entity: Customer, id: Option[Int],
created: Option[Instant], updated: Option[Instant]): Customer = {
entity.copy(id = id, created = created, updated = updated)
}
}
现在,我要加入客户表"和客户表",并将结果映射到名为CustomerWithAccount的案例类中. 我尝试了以下代码
Now I Want to join Customer Table and Account Table and map the result to a case class named CustomerWithAccount I have tried the following code
case class CustomerDetail(id: Option[Int],
status: String,
name: String)
object Customers extends GenericService[Customer, CustomerTable] {
override val table = TableQuery[CustomerTable]
val accountTable = TableQuery[AccountTable]
def getAllCustomersWithAccount = db.run(table.join(accountTable).on(_.id === _.id).map { row =>
//for (row1 <- row) {
for {
id <- row._1.id
status <- row._1.status.toString()
name <- row._2.name.toString()
} yield CustomerDetail(id = id, status = status, name = name)
//}
}.result)
override def copyEntityFields(entity: Customer, id: Option[Int], created:Option[Instant], updated: Option[Instant]): Customer = {
entity.copy(id = id, created = created, updated = updated)
}
}
但是这没有用. 请帮助我.
But this did not work. Please help me.
推荐答案
您可以尝试此查询
db.run((table.join(accountTable).on(_.id === _.id)
.map{
case (t,a) => ((t.id, t.status, a.name) <> (CustomerDetail.tupled, CustomerDetail.unapply _))
}).result)
这篇关于如何连接两个表并将结果映射到Slick中的case类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!