Slick 3.0.0 - 更新只有非空值的行 [英] Slick 3.0.0 - update row with only non-null values

查看:96
本文介绍了Slick 3.0.0 - 更新只有非空值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有一个包含列的表

  class Data(tag:Tag)extends Table [DataRow](tag,data ){
def id = column [Int](id,O.PrimaryKey)
def name = column [String](name)
def state = column [State] (state)
def price = column [Int](price)

def * =(id。?,name,state,price)< ((DataRow.apply _)。tupled,DataRow.unapply)
}



'I' d喜欢编写一个可以选择单行的函数,并更新提供的值不为空的列。

  def update(id:Int,name:Option [String],state:Option [State],price:Option [Int])

例如,

update(1,None,None,Some(5))会只更新数据行1的价格,使名称和状态保持不变

update(1,Some(foo),None,一些(6))会更新名称和价格,但保留其状态。



我想可以使用一些智能映射,但我很难表达它,不确定它如何根据输入(它们的值被定义)吐出不同长度的元组,因为它们或多或少是不相关的类。

  def update(id:Int,name:Option [String],state:Option [State],price:Opti on [Int])= {
table.fiter(_。id == id)。 ???? .update(name,state,price)
}


解决方案

建立在 JonasAnso's答案,将其转换为slick v3.0 +,并将其放入一个事务中:

  def partialUpdate(id :Int,name:Option [String],login:Option [String]):Future [Int] = {
val selectQ = users.filter(_。id === id)

val query = selectQ.result.head.flatMap {data =>
selectQ.update(data.patch(name,login))
}

db.run(query)
}


Having a table with the columns

class Data(tag: Tag) extends Table[DataRow](tag, "data") {
  def id = column[Int]("id", O.PrimaryKey)
  def name = column[String]("name")
  def state = column[State]("state")
  def price = column[Int]("price")

  def * = (id.?, name, state, price) <> ((DataRow.apply _).tupled, DataRow.unapply)
}

I'd like to write a function that would select a single row, and update the columns where the supplied values are not null.

def update(id: Int, name: Option[String], state: Option[State], price: Option[Int])

eg.

update(1, None, None, Some(5)) would update only the price of the data row 1, leaving the name and state intact

update(1, Some("foo"), None, Some(6)) would update the name and price, but leave its state intact.

I guess some smart mapping could be used, but I'm having a hard time expressing it, not sure how it could spit out different length tuples depending on the inputs (wether their value is defined), since they are more or less "unrelated" classes.

def update(id: Int, name: Option[String], state: Option[State], price: Option[Int]) = {
  table.fiter(_.id == id). ???? .update(name, state, price)
}

解决方案

Building on JonasAnso's answer, converting that to slick v3.0+, and putting it into a transaction:

  def partialUpdate(id: Int, name: Option[String], login: Option[String]): Future[Int] = {
    val selectQ = users.filter(_.id === id)

    val query = selectQ.result.head.flatMap { data =>
      selectQ.update(data.patch(name, login))
    }

    db.run(query)
  }

这篇关于Slick 3.0.0 - 更新只有非空值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆