目前我有这样的事情:
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)
但光滑不喜欢这个。使用Monomorphic case类和slick的CaseClassShape不起作用,因为它只支持内置类型,即我可以使用:
yield DeptEmployeeRow(department.name, employee.name)
但不是
yield DeptEmployeeRow(department, employee)
答案 0 :(得分:1)
元组实际上非常强大,特别是在模式匹配的上下文中。例如,您可以像这样访问您的元组内容:
M[a:b]
使用模式匹配访问元组:
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)
}
你可以进一步建模1:n关系:
val result2: DeptEmployeeRow = db.run(q.result).map(_.map(DeptEmployeeRow.tupled))