【问题标题】:How to insert the record that has a foreign key using lifted embedded syntax on slick如何在 slick 上使用提升的嵌入式语法插入具有外键的记录
【发布时间】:2014-07-01 23:15:30
【问题描述】:

我想插入一个包含外键的新记录。 比如向bars插入新记录,新记录的id是foos表查询结果找到的。

这是一个代码示例:

import scala.slick.driver.H2Driver.simple._

object Test {
  case class FooRecord(id:Int, str: String)
  class Foos(tag: Tag)  extends Table[FooRecord](tag, "users") {
    def id  = column[Int]("ID", O.PrimaryKey)
    def str = column[String]("EMAIL", O.NotNull)
    def * = (id, str) <> (FooRecord.tupled, FooRecord.unapply _)
  }
  val foos = TableQuery[Foos]

  case class BarRecord(app_id:Int, name: String)
  class Bars(tag: Tag)  extends Table[BarRecord](tag, "apps") {
    def foo_id = column[Int]("FOO_ID")
    def str    = column[String]("STR", O.NotNull)
    def * = (foo_id, str) <> (BarRecord.tupled, BarRecord.unapply _)
    def foo_fk = foreignKey("FOO_FK", foo_id, foos)(_.id)
  }
  val bars = TableQuery[Bars]

  def main(args: Array[String]): Unit = {
    Database.forURL("jdbc:h2:mem:test1", driver = "org.h2.Driver") withSession {
      implicit session =>
        foos.filter(_.str === "ABC").map { f =>
          // Insert a new record that contains foo's id as a foreign key to bars.

          // bars.insert(BarRecord(f.id, "DEF"))

          // [error]  found   : scala.slick.lifted.Column[Int]
          // [error]  required: Int

          bars.insert(BarRecord(1, "DEF"))       // OK
        }
    }
  }
}

我得到一个编译错误。外键的类型是 Column[Int],但 BarRecord id 类型是 Int。 有什么好方法可以获取 Int 值吗?或者有没有更优雅的方法可以插入来自另一个表的查询结果的值?

【问题讨论】:

    标签: scala insert foreign-keys slick


    【解决方案1】:

    您的查询返回提升的查询,而不是 Int 值:

    val fooIdColumn: lifted.Query[lifted.Column[Int], Int] = 
      foos.filter(_.str === "ABC").map(f => f.id)
    

    您可以使用run 并取回Seq[Int](因为可能有多个结果):

    val fooIds: Seq[Int] = 
      foos.filter(_.str === "ABC").map(x => x.id).run
    

    firstOptiongetOrElse 取回Int

    val fooId: Int = 
      foos.filter(_.str === "ABC").map(x => x.id).firstOption.getOrElse(0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多