Scala slick 3.3.x 将 filterOpt 与 OR 相结合

问题描述 投票:0回答:1

我在 scala 中有两个选项 seq 字符串:

val firstSeq = Some(Seq("1", "2", "3"))
val secondSeq = Some(Seq("car", dog", "cat"))

我正在使用灵活的查询查询oracle db中的数据:

(for {
  number <- numbers
    .filterOpt(firstSeq)((table, gs) => table.count.inSetBind(gs) && table.type === NumberType.Numeric)
    .filterOpt(secondSeq)((table, rs) => table.count.inSetBind(rs) && table.type === NumberType.String)
} yield {
  number
}).result

有没有办法通过 OR 条件将这两个 filterOpt 方法组合成一个?

scala slick
1个回答
0
投票

基于filterOpt方法的

scaladoc

  /** Applies the given filter, if the Option value is defined.
    * If the value is None, the filter will not be part of the query. */

仅当作为参数传递的

Option
Some
时,条件才会添加到查询中。在这种情况下,您有两个
Seq
。一种可能的解决方案是定义一个
case class
来包含 两个集合,然后将其传递给包裹在
filterOpt
内的
Option
。您还可以定义
Tuple
而不是案例类。

case class BothSeqs(first: Seq[Int], second: Seq[String])

val firstSeq = Seq("1", "2", "3")
val secondSeq = Seq("car", "dog", "cat")

val bothSeqs = BothSeqs(firstSeq, secondSeq)

numbers
  .filterOpt(Some(bothSeqs))((table,seqs) => 
      (table.count.inSetBind(seqs.first) && table.type === NumberType.Numeric)
        || (table.count.inSetBind(seqs.second) && table.type === NumberType.String)
  )
© www.soinside.com 2019 - 2024. All rights reserved.