【问题标题】:SLICK: A simple query using union and parameter listsSLICK:使用联合和参数列表的简单查询
【发布时间】:2015-05-05 22:46:34
【问题描述】:

我是 SLICK (2.1) 的新手,在使用 union 创建我的第一个查询时迷失了方向。因为这些参数最终是从外部(通过 Web 界面)提供的,所以我将它们设置为可选的。请参阅下面代码中的注释。如何创建合适的查询?

我的实际课程更复杂,为了这个问题,我对其进行了简化。

case class MyStuff(id: Int, value: Int, text: String)

class MyTable (tag: Tag) extends Table[MyStuff](tag, "MYSTUFF"){

  def id = column[Int]("ID", O NotNull)
  def value = column[Int]("VALUE", O NotNull)
  def text = column[String]("TEXT", O NotNull)

  def * = 
  (id, 
  value, 
  text).shaped <> ((MyStuff.apply _).tupled, MyStuff.unapply)
}

object myTable extends TableQuery(new MyTable(_)){
  def getStuff(ids: Option[List[Int]], values: Option[List[Int]])(implicit session: Session): Option[List[MyStuff]] = {
    /*
    1) If 'ids' are given, retrieve all matching entries, if any.
    2) If 'values' are given, retrieve all matching entries (if any), union with the results of the previous step, and remove duplicate entries.
    4) If neither 'ids' nor 'values' are given, retrieve all entries.
    */
  }
}

getStuff 是这样调用的:

db: Database withSession { implicit session =&gt; val myStuff = myTable.getStuff(...) }

【问题讨论】:

  • O NotNull 不应显式写入。这是 Slick 中的默认设置。

标签: scala slick slick-2.0


【解决方案1】:

如果值为 Some,则可以使用 inset,否则为文字 false,并且仅在某些不是 None 时过滤。

  if(ids.isDefined || values.isDefined)
    myTable.filter(row =>
      ids.map(row.id inSet _).getOrElse(slick.lifted.LiteralColumn(false))
    ) union myTable.filter(row =>
      values.map(row.value inSet _).getOrElse(slick.lifted.LiteralColumn(false))
    )
  else myTable

【讨论】:

    【解决方案2】:

    如果我对您的理解正确,您想在运行时从给定的输入构建一个过滤器。您可以查看 3.0 (http://slick.typesafe.com/doc/3.0.0-RC1/queries.html#sorting-and-filtering) 的扩展文档,位于“使用“动态过滤器”构建标准,例如来自网络表单”。这部分文档也适用于 2.1 版。

    【讨论】:

    • 从链接的文档中我了解到我的查询应该是这样的: def getStuff(ids: Option[List[Int]], values: Option[List[Int]]) = myTable.filter { myTable => List( ids.map(myTable.id === _), values.map(myTable.value === _) ).distinct } 失败并出现各种错误(推断类型参数,类型不匹配,类型 T 不能是一个查询条件)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多