问题
Can I build update query with variable number of fields without using plain SQL ?
For example update of single column is simple - I just yield it to create narrow query.
Query(RolesTable).filter((role: RolesTable.type) => role.id === role_id).map((role: RolesTable.type) => role.name).update(name)
But what if Role
has 5 fields and I want to allow API client to send me fields he wants to update ? How would I construct such query ?
回答1:
The key here is to use the ~
operator when yielding the selected columns. Using the example model from the documentation:
case class User(id: Option[Int], first: String, last: String)
object UsersTable extends Table[User]("users") {
def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
def first = column[String]("first")
def last = column[String]("last")
def * = id.? ~ first ~ last <> (User, User.unapply _)
}
A select based on your example would look like this:
val cols = Query(UsersTable).filter((user: UsersTable.type) => user.id === userId).map((user: UsersTable.type) => user.first ~ user.last)
And then the update
call would be:
cols.update((newFirst,newLast))
Also, if you wanted, you could re-write your select as a for comprehension as it shortens it up a bit:
val cols = for(user <- UsersTable if (user.id === userId)) yield user.first ~ user.last
cols.update((newFirst,newLast))
来源:https://stackoverflow.com/questions/16756086/can-i-build-update-query-with-variable-fields-without-using-plain-sql