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

2024-04-09

目前我有这样的事情:

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 的 CaseClassShape 不起作用,因为它只支持内置类型,即我可以使用:

yield DeptEmployeeRow(department.name, employee.name)

but not

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))
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Slick 3 从查询中返回自定义案例类 的相关文章

随机推荐