gpt4 book ai didi

scala - 如何连接两个表并将结果映射到 slick 中的案例类

转载 作者:行者123 更新时间:2023-12-02 09:24:05 24 4
gpt4 key购买 nike

我在一个使用 scala play 2 框架的项目中工作,我使用 slick 作为 FRM 和 postgres 数据库。

在我的项目中,客户是一个实体。所以我也创建了一个客户表和客户案例类和对象。另一个实体是账户。所以我也创建了一个帐户表和帐户案例类和对象。代码如下

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 的案例类我试过下面的代码

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)
}
}

但这没有用。请帮助我。

最佳答案

你可以试试这个查询

db.run((table.join(accountTable).on(_.id === _.id)
.map{
case (t,a) => ((t.id, t.status, a.name) <> (CustomerDetail.tupled, CustomerDetail.unapply _))
}).result)

关于scala - 如何连接两个表并将结果映射到 slick 中的案例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39316792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com