如何将查询中的外键 ID 传递给更新的行元素?
How to pass a foreign key id from query to the updating row element?
我正在使用 Slick 3.3.0 并且我有一个更新密码的用例 table 但是查找元素是一个叫做 LoginInfo
的东西,然后链接到目标可更新PasswordInfo
通过其 user_id
这是我的用例的一个非常简化的版本:
def update(id: Long, hasher: String, password: String, salt: Option[String]): Future[ExtPasswordInfo] = {
// first look up a loginInfo by some id, then find the connected userId and use
// it to update the PasswordInfo.
val action = (for {
loginInfo <- LoginInfo if loginInfo.id === id
passwordInfo <- PasswordInfo if passwordInfo.userId === loginInfo.userId
} yield passwordInfo).update(PasswordInfoRow(??? /* <<<< I need userId here */, hasher, password, salt))
db.run(action)
}
但是在查询产生 passwordInfo
并且我链接 update
方法后,我无法访问 userId
键。
如果可能的话我需要:
... yield passwordInfo).update(pi => PasswordInfoRow(pi.userId, ...
如何在 Slick 中执行此操作?
经过深思熟虑后,我这样解决了:
def update(id: Long, hasher: String, password: String, salt: Option[String]): Future[ExtPasswordInfo] = {
// first look up a loginInfo by some id, then find the connected userId and use
// it to update the PasswordInfo.
val action = (for {
userId <- LoginInfo.filter(_.id === id).result.head.map(_.userId)
} yield userId).flatMap { userId =>
val updated = PasswordInfoRow(userId, hasher, password, salt)
PasswordInfo.update(updated).map(_ => updated.toExt)
}.transactionally()
db.run(action)
}
我正在使用 Slick 3.3.0 并且我有一个更新密码的用例 table 但是查找元素是一个叫做 LoginInfo
的东西,然后链接到目标可更新PasswordInfo
通过其 user_id
这是我的用例的一个非常简化的版本:
def update(id: Long, hasher: String, password: String, salt: Option[String]): Future[ExtPasswordInfo] = {
// first look up a loginInfo by some id, then find the connected userId and use
// it to update the PasswordInfo.
val action = (for {
loginInfo <- LoginInfo if loginInfo.id === id
passwordInfo <- PasswordInfo if passwordInfo.userId === loginInfo.userId
} yield passwordInfo).update(PasswordInfoRow(??? /* <<<< I need userId here */, hasher, password, salt))
db.run(action)
}
但是在查询产生 passwordInfo
并且我链接 update
方法后,我无法访问 userId
键。
如果可能的话我需要:
... yield passwordInfo).update(pi => PasswordInfoRow(pi.userId, ...
如何在 Slick 中执行此操作?
经过深思熟虑后,我这样解决了:
def update(id: Long, hasher: String, password: String, salt: Option[String]): Future[ExtPasswordInfo] = {
// first look up a loginInfo by some id, then find the connected userId and use
// it to update the PasswordInfo.
val action = (for {
userId <- LoginInfo.filter(_.id === id).result.head.map(_.userId)
} yield userId).flatMap { userId =>
val updated = PasswordInfoRow(userId, hasher, password, salt)
PasswordInfo.update(updated).map(_ => updated.toExt)
}.transactionally()
db.run(action)
}