5

Scala に次のコードがあります。

case class Product(id: Option[Long] = None, name: String, price: BigDecimal, description: String)

object Products extends Table[Product]("product") {
  def id = column[Long]("id", O.AutoInc, O.PrimaryKey)
  def name = column[String]("name", O.NotNull)
  def price = column[BigDecimal]("price", O.NotNull)
  def description = column[String]("description", O.NotNull)

  def * = id.? ~ name ~ price ~ description <>(Product.apply _, Product.unapply _)

  def autoInc = * returning id

  def add(product: Product)(implicit s:Session): Long = {
    Products.autoInc.insert(product)
  }

  def all(implicit s:Session): List[Product] = {
    Query(Products).list
  }
}

すべての製品をリストすることはうまくいきますが、メソッドを追加することはできません。

呼び出し後:

val myProduct = models.Product(id = None, name = "test2", price = BigDecimal(2.99), description = "test3")
models.Products.add(myProduct)

PostgreSQL から、ID を null にすることはできないというエラー メッセージが常に表示されます。私はそれに完全に同意しますが、なぜid列がautoIncによって設定されていないのですか? そのように機能しませんか?

私はプレイを使っています!2.1.2、Scala 2.10.0、PostgreSQL 9.3、および play-slick 0.3.3。

前もって感謝します。

4

1 に答える 1

5

ここに提案があります。あなたを書き直してautoInc、次のようなメソッドを追加してください:

def autoInc = name ~ price ~ description returning id

def add(product: Product)(implicit s:Session): Long = {
    Products.autoInc.insert(p.name, p.price, p.description)
}

一部のデータベースでは、自動インクリメント列に null を挿入できません。多分それはPostgresのケースです。

于 2013-07-14T04:07:41.903 に答える