Slick query for one to optional one (zero or one) relationship

79 views Asked by At

Given tables of:

case class Person(id: Int, name: String)
case class Dead(personId: Int)

and populated with:

Person(1, "George")
Person(2, "Barack")
Dead(1)

is it possible to have a single query that would produce a list of (Person, Option[Dead]) like so?

(Person(1, "George"), Some(Dead(1)))
(Person(2, "Barack"), None)
1

There are 1 answers

1
Roman On BEST ANSWER

For slick 3.0 it should be something like this:

val query = for {
  (p, d) <- persons joinLeft deads on (_.id === _.personId)
} yield (p, d)

val results: Future[Seq[(Person, Option[Dead])]] = db.run(query.result)

In slick, outer joins are automatically wrapped in an Option type. You can read more about joining here: http://slick.typesafe.com/doc/3.0.0/queries.html#joining-and-zipping