以下のコードはほとんどの場合それ自体で説明していると思いますが、ここで簡単に説明します。
クエリ条件に追加する必要がある ID のリストがあります。条件をクエリに簡単に「AND」することはできますが (以下をval incorrect
参照)、条件を「OR」する良い方法を思い付くのに苦労しています。
ID のリストは静的ではありません。例としていくつか入れました。可能であれば、for 内包表記を使用する方法と、for 内包表記を使用しない方法を知りたいです。
また、コードを実行したい場合は、このコードを repl にドロップして、いくつかのインポートを追加できるはずです。
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)))
}