如何将列默认值设置为Null? (简单地说)

时间:2016-09-14 01:23:57

标签: scala slick slick-3.0

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)

}

创建具有此类结构的表后,表中的所有列都为Not Null

那么如何将它们设置为Nullable并将其值设置为Null

1 个答案:

答案 0 :(得分:6)

我们可以通过在nullable

中将Option[T]字段声明为case class来实现此目的

假设我们有User个班级,我们希望age值为nullable,且默认值为null。所以我们在下面声明我们的类。通知年龄为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)
}

年龄字段可以为空,其默认值为空