I think the code below mostly speaks for itself, but here's a short explanation.
I have a list of ids that need to be added to a query condition. I can easily "and" the conditions onto the query (see val incorrect
below), but am having trouble coming up with a good way to "or" the conditions.
The list of ids is not static, I just put some in there as an example. If possible, I'd like to know how to do it using a for comprehension, and without using a for comprehension.
Also, you should be able to drop this code in a repl and add some imports if you want to run the code.
object Tbl1Table {
case class Tbl1(id:Int, gid: Int, item: Int)
class Tbl1Table(tag:Tag) extends Table[Tbl1](tag, "TBL1") {
val id = column[Int]("id")
val gid = column[Int]("gid")
val item = column[Int]("item")
def * = (id, gid, item) <> (Tbl1.tupled, Tbl1.unapply)
}
lazy val theTable = new TableQuery(tag => new Tbl1Table(tag))
val ids = List((204, 11), (204, 12), (204, 13), (205, 19))
val query = for {
x <- theTable
} yield x
println(s"select is ${query.selectStatement}")
//prints: select is select x2."id", x2."gid", x2."item" from "TBL1" x2
val idsGrp = ids.groupBy(_._1)
val incorrect = idsGrp.foldLeft(query)((b, a) =>
b.filter(r => (r.gid is a._1) && (r.item inSet(a._2.map(_._2))))
)
println(s"select is ${incorrect.selectStatement}")
//prints: select is select x2."id", x2."gid", x2."item" from "TBL1" x2
// where ((x2."gid" = 205) and (x2."item" in (19))) and
// ((x2."gid" = 204) and (x2."item" in (11, 12, 13)))
//but want to "or" everything, ie:
//prints: select is select x2."id", x2."gid", x2."item" from "TBL1" x2
// where ((x2."gid" = 205) and (x2."item" in (19))) or
// ((x2."gid" = 204) and (x2."item" in (11, 12, 13)))
}