从连接查询重建对象树

时间:2017-02-18 01:19:31

标签: scala slick

我们假设我有以下数据库模型(不是真实案例,所以请原谅我这个例子的完全愚蠢):

enter image description here

我想从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}}本身。

0 个答案:

没有答案