Question

I am new to Scala and Anorm, but am trying my best to give it a good shot. I am stuck right now on trying to populate a child list of objects.

For example sake, I have a contact that has multiple phone numbers. How would I go about filling in my phone numbers from the database?

Scala

case class Contact(id: long, phoneNumbers: List[PhoneNumber])
case class PhoneNumber(area: String, rest: String)

Table Structure

Contact
  id bigint

PhoneNumber
 area varchar(3)
 rest varchar(7)
 contact_id bigint
Was it helpful?

Solution

You can try something like this:

val contacts: Iterable[Contact] = SQL(
  """
    SELECT c.id, p.area, p.rest
    FROM PhoneNumber p
    JOIN Contact c on p.contact_id = c.id;
  """
).as(long("id") ~ str("area") ~ str("rest") map(flatten) *
).groupBy(_._1).map {
  case (k,l) => Contact(k, l.map {
    d => PhoneNumber(d._2, d._3)
  })
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top