如何使用光滑3插入具有foregin键的记录?

时间:2016-07-12 15:04:49

标签: scala playframework slick slick-3.0 play-slick

我有两种模式:

case class User(uid: Option[Int], email: String, password: String, created_at: Timestamp, updated_at: Timestamp)

case class UserProfile(firstname: String, lastname: String, gender: Int, user_id: Long),

定义了用户表的DAO:

package dao

import java.sql.Timestamp

import scala.concurrent.{Await, Future}
import javax.inject.Inject

import models.{User, UserProfile}
import play.api.db.slick.DatabaseConfigProvider
import play.api.db.slick.HasDatabaseConfigProvider
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import slick.driver.JdbcProfile
import slick.profile.SqlProfile.ColumnOption.SqlType
import scala.concurrent.duration._
import com.github.t3hnar.bcrypt._

class UsersDAO @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends HasDatabaseConfigProvider[JdbcProfile] {
  import driver.api._

  private val Users = TableQuery[UsersTable]
  private val UsersProfile = TableQuery[UserProfileTable]


  def all(): Future[Seq[User]] = db.run(Users.result)

  def insert(user: User): Future[Int] = {
    println("coming inside insert of user dao")
    println(user)
//    insertUP(user)
    val hashPassword = user.password.bcrypt
    val updatedUser = user.copy(password = hashPassword)

    val query = db.run((Users returning Users.map(_.uid)) += updatedUser)
//    val uid = Await.result(query, 30 seconds)
//    println(s"UID ---------> $uid")
    query
  }




  def findByEmail(email: String): Option[User] = {

    val query = for {
      u <- Users if u.email === email
    } yield u

    val f: Future[Option[User]] = db.run(query.result).map(_.headOption)
    val result = Await.result(f, 30 seconds)
    println(result.isDefined)
    result
  }

  def authenticate(username: String, password: String): Future[Option[User]] = {

    val query = db.run(Users.filter(_.email === username).result.map(_.headOption.filter(user => password.isBcrypted(user.password)))).map(_.headOption)

    query
  }

  private class UsersTable(tag: Tag) extends Table[User](tag, "users") {

    def uid = column[Int]("uid", O.PrimaryKey, O.AutoInc, O.SqlType("INT"))
    def email = column[String]("email")
    def password = column[String]("password")
    def created_at = column[Timestamp]("created_at", SqlType("timestamp not null default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP"))
    def updated_at = column[Timestamp]("updated_at", SqlType("timestamp not null default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP"))
    def idx = index("email_UNIQUE", email, unique = true)

    def * = (uid.?, email, password, created_at, updated_at) <> (User.tupled, User.unapply _)
  }

  private class UserProfileTable(tag: Tag) extends Table[UserProfile](tag, "user_profile"){

    def firstname = column[String]("firstname")
    def lastname = column[String]("lastname")
    def gender = column[Int]("gender")
    def user_id = column[Int]("user_id")

    def * = (firstname, lastname, gender, user_id) <> (UserProfile.tupled, UserProfile.unapply)

    def fk_user_id = foreignKey("fk_user_id", user_id, Users)(_.uid)
  }



}

在insert函数中,如何在同一函数或调用中将uid添加到用户配置文件表的user_id字段?

编辑1

尝试了Pawel建议的解决方案,但获得例外:

failed slick.SlickException: This DBMS allows only a single AutoInc column to be returned from an INSERT

编辑 - 2

现在,在尝试了一些解决方案之后,insert函数是这样的:

def insert(user: User): Future[Int] = {
    val hashPassword = user.password.bcrypt
    val updatedUser  = user.copy(password = hashPassword)

    val insertUser = (Users returning Users.map(_.uid)) += updatedUser
    def insertUserProfile(updatedUserProfile: UserProfile) = (UsersProfile returning UsersProfile.map(_.user_id)) += updatedUserProfile

    val insertUserThenProfile = for {
      createdUserId        <- insertUser
      createdUserProfileId <- insertUserProfile(UserProfile("First name", "Last name", gender = 0, user_id = createdUserId))
    } yield createdUserProfileId

    db.run(insertUserThenProfile.transactionally)
  }

但仍然收到错误: failed slick.SlickException: This DBMS allows only a single AutoInc column to be returned from an INSERT

解决方案

Pawels解决方案应该可以正常工作,但是有些DBMS会因为没有返回AUtoInc字段而提供异常,并且尝试返回其他内容。 您可以在文档中看到注释: http://slick.lightbend.com/doc/3.0.0/queries.html

Note

Many database systems only allow a single column to be returned which must be the table’s auto-incrementing primary key. If you ask for other columns a SlickException is thrown at runtime (unless the database actually supports it).

所以,现在,我的模型是这样的:

case class User(uid: Option[Int], email: String, password: String, created_at: Timestamp, updated_at: Timestamp)

case class UserProfile(upid: Option[Int], firstname: String, lastname: String, gender: Int, user_id: Int)

表类:

private class UserProfileTable(tag: Tag) extends Table[UserProfile](tag, "user_profile"){

    def upid= column[Int]("upid", O.PrimaryKey, O.AutoInc, O.SqlType("INT"), O.Default(0))
    def firstname = column[String]("firstname")
    def lastname = column[String]("lastname")
    def gender = column[Int]("gender")
    def user_id = column[Int]("user_id")

    def * = (upid.?, firstname, lastname, gender, user_id) <> (UserProfile.tupled, UserProfile.unapply)

    def fk_user_id = foreignKey("fk_user_id", user_id, Users)(_.uid)
  }

最后插入方法:

def insert(user: User): Future[Int] = {
    val hashPassword = user.password.bcrypt
    val updatedUser  = user.copy(password = hashPassword)

    val insertUser = (Users returning Users.map(_.uid)) += updatedUser
    def insertUserProfile(updatedUserProfile: UserProfile) = (UsersProfile returning UsersProfile.map(_.upid)) += updatedUserProfile

    val insertUserThenProfile = for {
      createdUserId        <- insertUser
      createdUserProfileId <- insertUserProfile(UserProfile(Some(0), "First name", "Last name", gender = 0, user_id = createdUserId))
    } yield createdUserProfileId

    db.run(insertUserThenProfile.transactionally)
  }

2 个答案:

答案 0 :(得分:1)

进行查询以插入新成员并返回其成员

的成员
val memberWithId = (queryMember returning queryMember.map(_.id) into ((c, id) => c.copy(id = id))) += registerMember.copy(password = pwHash)

然后将查询实现为事务。插入成员,插入用户配置文件(您可以使用第一个语句成功的ID)

val transaction = (for {
  m: Member <- memberWithId
  p: UsersProfile <- queryProfile returning queryProfile += MemberProfile(m.id, firstName, ...)
} yield m).transactionally

将其作为Try运行,以便您可以更轻松地解析错误而不是崩溃。

db.run(transaction.asTry)

答案 1 :(得分:1)

我不知道您打算如何为UserProfile提供值(这取决于您,可能是insert方法中的其他参数),但我会尝试这样的事情:< / p>

def insert(user: User): Future[UserProfile] = {
  val hashPassword = user.password.bcrypt
  val updatedUser  = user.copy(password = hashPassword)

  val insertUser = (Users returning Users.map(_.uid)) += updatedUser
  def insertUserProfile(updatedUserProfile: UserProfile) = (UsersProfile returning UsersProfile.map(_.user_id)) += updatedUserProfile

  val insertUserThenProfile = for {
    createdUserId        <- insertUser
    createdUserProfileId <- insertUserProfile(UserProfile("First name", "Last name", gender = 0, user_id = createdUserId))
  } yield createdUserProfileId

  db.run(insertUserThenProfile.transactionally)
}