我有以下代码将行插入名为 luczekInfo 的表和函数以从数据库中获取数据。我的问题是如何在 get(id) 函数返回的行上创建函数来更新表 luczekInfo 中的列。在 Slick 中更新列值的最佳方法是什么?
def create(profil: luczekInfo): Either[Failure, luczekInfo] = {
try {
val id = db.withSession {
LuczekInfo returning LuczekInfo.id insert profil
}
Right(profil.copy(id = Some(id)))
} catch {
case e: SQLException =>
Left(databaseError(e))
}
}
def get(id: Int): Either[Failure, luczekInfo] = {
try {
db.withSession {
LuczekInfo.findById(id).firstOption match {
case Some(profil: luczekInfo) =>
Right(profil)
case _ =>
Left(notFoundError(id))
}
}
} catch {
case e: SQLException =>
Left(databaseError(e))
}
}
提前感谢您的回答。
最佳答案
光滑 2.X
您可以通过两种方式更新一行(据我所知),第一种是创建 luczekInfo#TableElementType
类型的行对象。并使用它来更新整行:
def updateById(id: Long, row: luczekInfo#TableElementType)(implicit s: Session): Boolean =
luczekInfo.filter(_.id === id).update(row)
或者您可以使用以下方法更新单个字段:
def updateNameById(mId: Long, mName: String)(implicit s: Session) = {
val q = for { l <- luczekInfo if l.id === mId } yield l.name
q.update(mName).run
}
我假设你的表有一个名为
name
的文件.您也可以在 Slick documentation 上找到它在更新部分。
光滑 3.1.X
insertOrUpdate
有额外的支持( upsert ) 操作:luczekInfo.insertOrUpdate(row)
关于scala - 更新 db row scala slick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23994003/