gpt4 book ai didi

Slick 3 从查询返回自定义案例类

转载 作者:行者123 更新时间:2023-12-02 03:18:14 25 4
gpt4 key购买 nike

目前我有这样的事情:

val q = for {
department <- departments if department.id === x
employee <- employees if employee.departmentId === department.id
} yield (department, employee)

这会给我:
(sales, john)
(sales, bob)
(finance, william)
(finance, helen)

然后我按部门对结果进行分组:
val grouped = results.groupBy(_._1).mapValues(_.map(_._2))

给我:
(sales -> (john, bob))
(finance -> (wiliam, helen)

我想避免元组。虽然在简单的例子中很清楚,如果我想要结构化格式的部门、经理、副手和员工名单,它很快就会变得难以管理。如果查询和结果处理在源代码中彼此不接近,则尤其如此。

我怎样才能在查询中产生除元组以外的其他东西?

我试图产生一个案例类:
case class DeptEmployeeRow(department: Department, employee: Employee)

val q = for {
department <- departments if department.id === x
employee <- employee if employee.id
} yield DeptEmployeeRow(department, employee)

但 slick 不喜欢这样。使用 Monomorphic case 类和 slick 的 CaseClassShape 不起作用,因为它只支持内置类型,即我可以使用:
yield DeptEmployeeRow(department.name, employee.name)

但不是
yield DeptEmployeeRow(department, employee)

最佳答案

元组实际上非常强大,尤其是在模式匹配的上下文中。例如,您可以像这样访问元组内容:

case class DeptEmployeeRow(department: Department, employee: Employee)

val q = for {
department <- departments if department.id === x
employee <- employees if employee.departmentId === department.id
} yield (department, employee)

使用模式匹配访问元组:
val result1: DeptEmployeeRow = db.run(q.result).map {
case (department, employee) => DeptEmployeeRow(department, employee)
}

或者使用快捷方式:
val result2: DeptEmployeeRow = db.run(q.result).map(_.map(DeptEmployeeRow.tupled))

您可以进一步建模 1:n 关系:
case class DeptWithEmployees(department: Department, employees: Seq[Employee])

val result3: DeptWithEmployees = db.run(q.result).map { results =>
results.groupBy(_._1).map { // assumption that _._1 is your department id
case (dept, grp) => DeptWithEmployees(dept, grp.map(_._2))
}
}

关于Slick 3 从查询返回自定义案例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35258379/

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