acmoune
acmoune

Reputation: 3411

How to group results with Slick

Let's say I have those two models:

case class Department(id: Long, title: String)
case class Program(id: Long, departmentId: Long, title: String)

And two TableQuery, departments and programs, based on Table mapped to those case classes respectively.

I would like to make a query returning a Seq[(Department, Seq[Program])], where I have a list of departments with their corresponding programs.

I started like this:

val query = 
  (departments join programs on ((d, p) => d.id === p.departmentId))
    .groupBy {...}

But what ever I put in the group by clause just doesn't make sense.

please help.

Upvotes: 0

Views: 479

Answers (2)

acmoune
acmoune

Reputation: 3411

@osehyum, thanks for your answer. Your query is returning this:

Map[Long, Seq[(Department, Program)]]

The Long here is for the Department Id.

I managed to turn it with this:

val query = departments.joinLeft(programs).on(_.id === _.departmentId).result
    .map(_.groupBy(_._1).toSeq)
    .map(items => items.map { case (dep, rows) =>
      (dep, rows.map(_._2).filter(_.isDefined).map(_.get))
    })

Note that I used joinLeft this time, so Program became Option[Program], so I had to filter and map. It is tested.

Upvotes: 1

osehyum
osehyum

Reputation: 145

How about this?

val query = departments.join(programs).on(_.id === _.departmentId)
        .result
        .map(_.groupBy(_._1.id))

db.run(query)

Upvotes: 0

Related Questions