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
?
答案 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)
}
年龄字段可以为空,其默认值为空