我们假设我有以下数据库模型(不是真实案例,所以请原谅我这个例子的完全愚蠢):
我想从db中获取连接结果,这样我就可以从Faculty
元素开始构造这些对象的树。
因此我会有以下案例类:
case class StudentWithGrades(student: Student, grades: Seq[Grade])
case class GroupWithStudents(group: Group, students: Seq[Student])
case class FacultyWithGroups(faculty: Faculty, groups: Seq[Group])
并且希望以这样的方式重建从db中检索的行,最后我只需要Seq[FacultyWithGroups]
。
有没有比这更简单的方法:
db.run (
FacultyTable
.join(GroupTable).on(_.id === _.facultyId)
.join(StudentTable).on(_._2.id === _.groupId)
.join(GradeTable).on(_._2.id === _.studentId)
.result
.map {
_.groupBy { case (((faculty, group), student), _) =>
(faculty, group, student)
}
.map { case ((faculty, group, student), groupped) =>
(faculty, group, StudentWithGrades(student, groupped.map(_._2)))
}
.toSeq
.groupBy { case (faculty, group, studentGrades) =>
(faculty, group)
}
.map { case ((faculty, group), groupped) =>
(faculty, GroupWithStudents(group, groupped.map(_._3)))
}
.toSeq
.groupBy { case(faculty, group) =>
faculty
}
.map { case(faculty, groupped) =>
FacultyWithGroups(faculty, groupped.map(_.2))
}
}
)
虽然它实际上与Slick
相关(以类似于经典ORM
的方式重建对象树),但在我看来,对于集合的巧妙处理,它基本上更像是一个问题。 {1}}本身。