2
我使用slick 3.1,Play框架2.5和scala 2.11。我的應用程序有'用戶'表,其中引用列'addressId'表示'地址'表的'id'列。我無法在這兩個表中插入數據。下面是該如何使用scala在play-slick中編寫包含引用列的表的插入查詢到另一個表?
此代碼的用戶窗體:
val registerForm: Form[RegisterForm] = Form {
mapping(
"id" -> optional(number),
"firstname" -> nonEmptyText.verifying("letters only", name => name.isEmpty || name.matches("[A-z\\s]+")),
"lastname" -> nonEmptyText.verifying("letters only", name => name.isEmpty || name.matches("[A-z\\s]+")),
"email" -> text.verifying(nonEmpty),
"password" -> text.verifying(nonEmpty),
"address" -> mapping(
"id" -> optional(number),
"city" -> nonEmptyText.verifying("letters only", name => name.isEmpty || name.matches("[A-z\\s]+")),
"state" -> text,
"country" -> text,
"pin" -> number
)(AddressForm.apply)(AddressForm.unapply)
)(RegisterForm.apply)(RegisterForm.unapply)
}
這是兩個模型類:
case class Address(id: Option[Int], city: String, state: String, country: String, pin: Int)
case class User(id: Option[Int], firstname: String, lastname: String, email: String, password: String, addressId: Option[Int])
這裏是映射到相應的數據庫表與表查詢兩類:
private class UserDB(tag: Tag) extends Table[User](tag, "user") {
def id = column[Option[Int]]("id", O.PrimaryKey, O.AutoInc)
def firstname = column[String]("firstname")
def lastname = column[String]("lastname")
def email = column[String]("email")
def password = column[String]("password")
def addressId = column[Option[Int]]("address_id")
override def * = (id, firstname, lastname, email, password, addressId) <> ((User.apply _).tupled, User.unapply)
def address_fk= foreignKey("fk_user_address", addressId, addressTable)(_.id)
}
private class AddressDB(tag: Tag) extends Table[Address](tag, "address") {
def id = column[Option[Int]]("id", O.PrimaryKey, O.AutoInc)
def city = column[String]("city")
def state = column[String]("state")
def country = column[String]("country")
def pin = column[Int]("pin")
override def * = (id, city, state, country, pin) <> ((Address.apply _).tupled, Address.unapply)
}
private val userTable = TableQuery[UserDB]
private val addressTable = TableQuery[AddressDB]
請告訴我如何插入數據到兩個相關的表使用光滑的查詢。
非常感謝您提前。
非常感謝@HüseyinZengin,它的工作和解決了我的問題。 – Govardhan
此查詢返回單位。如果我希望它返回Future [User]? – Govardhan
非常感謝@HüseyinZengin。 – Govardhan