由网友(顾你安稳)分享简介:目前我有这样的东西:val q = for {department <- departments if department.id === xemployee <- employees if employee.departmentId === department.id} yield (department, emp...![用过一次就爱上的可视化工具](https://p.xsw88.cn/allimgs/daicuo/20230903/4164.png)
目前我有这样的东西:
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)
![用过一次就爱上的可视化工具](https://p.xsw88.cn/allimgs/daicuo/20230903/4164.png)
然后我按部门对结果进行分组:
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)
但斯利克不喜欢这样。使用单态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))
}
}
相关推荐
最新文章