如何将列默认值设置为 Null? (光滑)

How to set a column default value to Null? (in slick)

case class Account(var email:String, var pass:String, var familyId: Int, var accessId: Int, id: Option[Int] = None)

// A Accounts table with 5 columns: id, email, pass, familyId, accessId
class Accounts(tag: Tag) extends Table[Account](tag, "ACCOUNTS") {

  def id = column[Int]("ID", O.AutoInc, O.PrimaryKey)
  def email = column[String]("EMAIL")
  def pass = column[String]("PASS")
  def familyId = column[Int]("FAMILY_ID")                            // TODO: add fk family_id
  def accessId = column[Int]("ACCESS_ID")                            // TODO: add fk access_id

  def * = (email, pass, familyId, accessId, id.?) <> (Account.tupled, Account.unapply)

}

在使用这种结构创建 table 之后,table 中的所有列都是 Not Null

那么如何将它们设置为Nullable并将它们的值设置为Null呢?

我们可以通过在 case class

中将 nullable 字段声明为 Option[T] 来做到这一点

假设我们有 User class,我们希望 age 值为 nullable,年龄的默认值为 null。所以我们声明我们的 class 如下。注意年龄是 Option[Int].

case class User(name: String, age: Option[Int])

class Users(tag: Tag) extends Table[User](tag, "users") {
  def name = column[String]("name")
  def age = column[Option[Int]]("age", O.Default(None)) //notice default value is None which translates to Null in database
  def * = (name, age) <> (User.tupled, User.unapply)
}

age 字段可以为 null,其默认值为 null