class ItemTable(tag: Tag) extends Table[Item](tag, _tableName = "items") {
def id: Rep[Int] = column[Int]("id", O.PrimaryKey, O.AutoInc)
def authId: Rep[String] = column[String]("auth_id")
def productId: Rep[Int] = column[Int]("product_id")
def position: Rep[Int] = column[Int]("position")
override def * : ProvenShape[Item] = (id, authId, productId, position) <> ((Item.apply _).tupled, Item.unapply)
}
class ItemService @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)(implicit executionContext: ExecutionContext) {
private lazy val query = TableQuery[ItemTable]
def updateItem(item: Item, previousPosition: Int): Future[Item] = {
if (previousPosition < item.position) {
// this is the sql I want to convert to slick
db.run(sqlu""" UPDATE #${query.baseTableRow.tableName} SET position = position - 1 WHERE position >= #$previousPosition AND position <= #${item.position} AND auth_id = '#${item.authId}'""")
}
else if (previousPosition > item.position) {
db.run(sqlu""" UPDATE #${query.baseTableRow.tableName} SET position = position + 1 WHERE position <= #$previousPosition AND position >= #${item.position} AND auth_id = '#${item.authId}' """)
}
else {
// some other code
}
}
}
case class Item(id: Int, authId: String, productId: Int, position: Int){}
我的SQL可以正常工作,我被困在这里将其翻译成光滑的代码。
val q2 = query.filter(f=> f.authId === item.authId && f.position >= previousPosition && f.position <= item.position)
//我不知道如何更新多个或将结果集传递给update函数
Slick的嵌入式样式不支持表单的动态突变批量更新SET position = position + 1
(Slick问题497)。
这意味着在这里使用正确的SQL风格是正确的方法。
关于惯用语的附加说明sqlu
:我注意到sqlu
您使用了“拼接”(#$
表名)。这样可以防止Slick将值视为字符串,这适合您的工作。但是,以后的用法#$previousPosition
通常会写成纯替换$previousPosition
。那是因为您通常希望Slick正确地转义那里的SQL参数。它可能对整数没有影响,但对其他数据类型则可能有所不同。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句