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