3

I have an update function in my UserDAO class that takes a few optional values:

def update(id: Int, name: Option[String], password: Option[String], age: Option[Int])

I know how to update all of the values:

val query = for {
    u <- users if u.id === id
} yield (u.name, u.password, u.age)

db.run(query.update(name.get, password.get, age.get))

But want to do it conditionally update the different columns, depending on if their Option value is defined. Something like this perhaps:

val query = for {
    u <- users if u.id === id
} yield (u.name if name.isDefined, u.password if password.isDefined, u.age if age.isDefined) // Pseudo code

db.run(query(update(...)) // Unpack arguments here
Tyler
  • 17,669
  • 10
  • 51
  • 89
  • what is your intention of doing .get in the line db.run(query.update(name.get, password.get, age.get)) actually it should be db.run(query.update(Some(name), Some(password), Some(age))) right??? – Jet Mar 03 '16 at 06:57
  • The `get` is because I am passing in values wrapped in options. But I only want to update columns that have an Option parameter that is defined. – Tyler Mar 03 '16 at 16:42
  • This question looks very similar to [another](http://stackoverflow.com/questions/35649319/slick-3-0-0-update-row-with-only-non-null-values) one asked a few days ago. No-one seems to know the answer though.. – hasumedic Mar 04 '16 at 09:01

1 Answers1

0

For slick 3, you can try like this,

    val query = for {
        u <- db.run(users.filter(_.id === id).result)
        u1 = if(u.nonEmpty && u.head.name.isDefined){
                u.head.copy(name = u.head.name) //add more if needed
              }
              else
             {
              u
             }
       res <- db.run(users.update(u1))
    } yield res

for slick 2 no need of for-yield

        val u = db.run(users.filter(_.id === id).result)
        val u1 = if(u.nonEmpty && u.head.name.isDefined){
                 u.head.copy(name = u.head.name) //add more if needed
                }
                else
                {
                 u
                }
        val res = db.run(users.update(u1))

Hope my answer was helpful.

cpawali
  • 268
  • 3
  • 12
Jet
  • 3,018
  • 4
  • 33
  • 48