Benny
Benny

Reputation: 3917

Complex Slick Join Query

I have multiple tables and I need to return them all together with a Slick query.

case class A(id: Int, name: String)
case class B(id: Int, name: String)
case class C(id: Int, name: String)
case class AtoC(aId: Int, dId: Int)
case class D(id: Int, name: String)

Assuming I have Table definitions matching the above case classes, I want to return something like (A, B, C, Seq[D]) but I cannot find a way to write it where it will even compile.

I have tried something like this:

for {
    a <- AQuery.innerJoin(B)....
    ...
    AtoC <~ a.innerJoin(AtoCQuery).on(....)

but this won't even compile.

Upvotes: 0

Views: 731

Answers (1)

Daniel Riquelme
Daniel Riquelme

Reputation: 301

Try something like this:

val q = for (
  ((((A, B), AtoC), C), D)
  <- AQuery.innerJoin(BQuery).on(_.id === _.id)   // A.id == B.id
    .innerJoin(AtoCQuery).on(_._1.id === _.aId)   // A.id == AtoC.aId
    .innerJoin(CQuery).on(_._2.cId === _.id)      // AtoC.cId == C.aId
    .innerJoin(DQuery).on(_._1._1._1.id === _.id) // A.id == D.id
) yield (A, B, C, D)
val result = q.run

This code is not tested. Hope it helps !

Regards

Upvotes: 1

Related Questions