Slick 3.0.0:如何查询一对多/多对多关系 [英] Slick 3.0.0: How to query one-to-many / many-to-many relations

查看:36
本文介绍了Slick 3.0.0:如何查询一对多/多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大约一年前,关于 slick 2.x (scala 光滑的一对多集合).我想知道反应浮油的发布是否有任何进展.

Basically the same question has been asked about a year ago for slick 2.x (scala slick one-to-many collections). I'm wondering if there has any progression been made with the release of reactive slick.

假设我们有三个表.librarybooklibrary_to_book,其中图书馆有很多书.我想要的是一个带有他们书籍的图书馆列表.在 Scala 中,这类似于 Seq[(Library, Seq[Book])].我的查询如下:

Let's say for example we have three tables. library, book and library_to_book where a library has many books. What I want is a list of libraries with their books. In scala this would be something like Seq[(Library, Seq[Book])]. The query I have is as follows:

val q = (for {
  l   <- libraries
  ltb <- libraryToBooks if l.id === ltb.libraryId
  b   <- books if ltb.bookId === b.id
} yield (l, b)
db.run(q.result).map( result => ??? )

results 在这种情况下是 Seq[(Library, Book)] 类型.我该如何更改查询以获得 Seq[(Library, Seq[Book])] 类型的结果?编写此类查询的巧妙方式"是什么?

results in this case is of type Seq[(Library, Book)]. How do I have to change my query to get a result of type Seq[(Library, Seq[Book])] instead? What is the "slick way" of writing such queries?

推荐答案

IMO 你的代码看起来不错.这实际上取决于对您来说更易读的内容.或者,您也可以使用 join:

IMO your code looks fine. It really depends on what feels more readable to you. Alternatively, you can use join as well:

val findBooksQuery = libraries
  .join(libraryToBooks).on(_.id === _.libraryId)
  .join(books).on(_.id === _._2.bookId)
  .result

val action = (for {
  booksResult <- findBooksQuery
} yield {
  booksResult.map { row =>
    val (libraryTableRow, libraryToBooksTableRow) = row._1
    val booksTableRow = row._2
    // TODO: Access all data from the rows and construct desired DS
  }
}

db.run(action)

然后您可以对特定键执行 groupBy 以获得您正在寻找的数据结构类型.在这种情况下,它会更加进化,因为它是跨三个表的连接.例如,将以下内容添加到您的查询中:

You can then do a groupBy on a particular key to get the kind of data structure you are looking for. In this case, it would be more evolved as it is join across three tables. Example, add following to your query:

val findBooksQuery = libraries
  .join(libraryToBooks).on(_.id === _.libraryId)
  .join(books).on(_.id === _._2.bookId)
  // To group by libraries.id
  .groupBy(_._1.id)
  .result

这篇关于Slick 3.0.0:如何查询一对多/多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆