scala - Slick 3.0.0: How to query one-to-many / many-to-many relations -
basically same question has been asked year ago slick 2.x (scala slick one-to-many collections). i'm wondering if there has progression been made release of reactive slick.
let's example have 3 tables. library
, book
, library_to_book
library has many books. want list of libraries books. in scala seq[(library, seq[book])]
. query have 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
in case of type seq[(library, book)]
. how have change query result of type seq[(library, seq[book])]
instead? "slick way" of writing such queries?
imo code looks fine. depends on feels more readable you. alternatively, can use join 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 data rows , construct desired ds } } db.run(action)
you can groupby on particular key kind of data structure looking for. in case, more evolved join across 3 tables. example, add following query:
val findbooksquery = libraries .join(librarytobooks).on(_.id === _.libraryid) .join(books).on(_.id === _._2.bookid) // group libraries.id .groupby(_._1.id) .result
Comments
Post a Comment