Search code examples
scalaslickslick-3.0

Multiple left joins using slick?


I have the following slick entities:

class Person(personId, houseId, carId)
class House(houseId)
class Car(carId)

I want to select a Person and their optional house and car, my query is:

val query = personTable
      .filter(_.personId === personId)
      .joinLeft(houseTable)
      .on(_.houseId === _.houseId)
      .joinLeft(carTable)
      .on(_._1.carId === _.carId)
      .result
      .headOption

However, the return type of the query looks a little funny, I'd expect it to be a tuple(person, house, car):

Option[(Person, Option[House], Option[Car])]

But it's actually a tuple(tuple(person, house), car):

Option[((Person, Option[House]), Option[Car])]

The data that comes back does seem correct, its just in an unusual structure, maybe I'm not performing the multiple joins correctly above?


Solution

  • Things look normal to me.

    If you don't like the current datatype, you can map in your query to change it, like this e.g:

    val query = personTable
          .filter(_.personId === personId)
          .joinLeft(houseTable)
          .on(_.houseId === _.houseId)
          .joinLeft(carTable)
          .on(_._1.carId === _.carId)
          .map{case((person, houseOpt), carOpt) => (person, houseOpt, carOpt)}
          .result
          .headOption