tiran
tiran

Reputation: 2431

scalaquery retrieve values

I have few tables, lets say 2 for simplicity. I can create them in this way,

...
val tableA = new Table[(Int,Int)]("tableA"){
def a = column[Int]("a")
def b = column[Int]("b")
}

val tableB = new Table[(Int,Int)]("tableB"){
def a = column[Int]("a")
def b = column[Int]("b")
}

Im going to have a query to retrieve value 'a' from tableA and value 'a' from tableB as a list inside the results from 'a' my result should be:

List[(a,List(b))]

so far i came upto this point in query,

def createSecondItr(b1:NamedColumn[Int]) = for(
    b2 <- tableB if b1 === b1.b
    ) yield b2.a

val q1 = for (
a1 <- tableA
listB = createSecondItr(a1.b)
) yield (a1.a , listB)

i didn't test the code so there might be errors in the code. My problem is I cannot retrieve data from the results.

to understand the question, take trains and classes of it. you search the trains after 12pm and you need to have a result set where the train name and the classes which the train have as a list inside the train's result.

Upvotes: 1

Views: 190

Answers (1)

Jens Schauder
Jens Schauder

Reputation: 81882

I don't think you can do this directly in ScalaQuery. What I would do is to do a normal join and then manipulate the result accordingly:

import scala.collection.mutable.{HashMap, Set, MultiMap}

def list2multimap[A, B](list: List[(A, B)]) = 
  list.foldLeft(new HashMap[A, Set[B]] with MultiMap[A, B]){(acc, pair) => acc.addBinding(pair._1, pair._2)}

val q = for (
     a <- tableA
     b <- tableB
     if (a.b === b.b)
) yield (a.a, b.a)

list2multimap(q.list)

The list2multimap is taken from https://stackoverflow.com/a/7210191/66686

The code is written without assistance of an IDE, compiler or similar. Consider the debugging free training :-)

Upvotes: 1

Related Questions