Slick 3.0.0 - update row with only non-null values

后端 未结 3 1113
攒了一身酷
攒了一身酷 2021-01-13 15:37

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         


        
3条回答
  •  心在旅途
    2021-01-13 15:50

    As I commented the question is similar to an existing one, but you don't seem to have any extra requirements.

    The simplest approach is just SELECT + UPDATE. For example you add a patch function in your DataRow class defining how you want to update your model

          def patch(name: Option[String], state: Option[State], price: Option[Int]): Data {
             this.copy(name = name.getOrElse(this.name), ...)
          }
    

    And you add a partialUpdate method in your repo class

    class DataRepo {
      private val Datas = TableQuery[Data]
      val db = ???
    
      def partialUpdate(id: Int, name: Option[String], state: Option[State], price: Option[Int]): Future[Int] = {
        val query = Datas.filter(_.id === id)
        for {
          data <- db.run(query.result.head)
          result <- db.run(query.update(data.patch(name, state, price)))
        } yield result
      }
    
    }
    

    As you see the main problem of this solution is that there are 2 SQL statements, SELECT and UPDATE.

    Other solution is to use plain SQL (http://slick.typesafe.com/doc/3.0.0/sql.html) but of course this gives other problems.

提交回复
热议问题