Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slick update return the updated object

Tags:

scala

slick

I'm trying to have a function return the updated object after the db runs an update method on the query right now, but I can't figure out how to successfully return the object. This is a function I wrote using examples I found, but I would like to extend q.update(cat) to return a Future[Cat].

def update(id: Long, cat: Cat): Future[Unit] = db.run {
  val q = for { c <- cats if c.id === id } yield c
  q.update(cat).map(_ => ())
}
like image 246
wesmelon Avatar asked Sep 26 '22 12:09

wesmelon


1 Answers

You should try the following:

def update(id: Long, cat: Cat): Future[Option[Cat]] = db.run {
  cats.filter(_.id === id).update(cat).map {
    case 0 => None
    case _ => Some(cat)
  }
}

You should return a Future[Option[Cat]] instead of a Future[Cat], because the cat with provided ID might not exist (the update method returns 0 value then). Violating integrity constraints will result in a Failure of the Future.

like image 181
Paweł Jurczenko Avatar answered Oct 04 '22 18:10

Paweł Jurczenko