Search code examples
scalacassandraphantom-dsl

How to update multiple fields in a row in phantom-dsl?


I am using Phantom 1.26.6.

// id is the primary key
case class Motorcycle(id:String, model:String, made:String, capacity:Int)

Give an instance of Motorcycle, which already exists in Cassandra, I would like to update the value of model, made, capacity.

// The following does not compile.
 update.where(_.id.eqs(bike.id)).modify(_.model.setTo(bike.model))
 .modify(_.make.setTo(bike.make))
 .modify(_.capacity.setTo(bike.capacity))


 // The following works.   
 val updateQuery = update.where(_.id.eqs(bike.id))

 for {
    _ <- updateQuery.modify(_.model.setTo(bike.model)).future()
    _ <- updateQuery.modify(_.make.setTo(bike.made)).future()
    result <- updateQuery.modify(_.capacity.setTo(bike.capacity)).future()
  } yield (result)

I wonder if there ia a better way of updating multiple fields.

Thanks in advance for any assistance !

Shing


Solution

  • All you have to do is to use the and operator to chain multiple update statements. This will execute everything in a single query.

     val updateQuery = update.where(_.id eqs bike.id)
       .modify(_model setTo bike.model)
       .and(_.make setTo bike.made)
       .and(_.capacity setTo bike.capacity)
       .future()