具有可选值的 Phantom 更新模型
Phantom update model with Optional values
我的模型有一个更新方法,它采用带有选项类型的 class,我想构建一个更新语句,其中包含一个动态 SET,具体取决于哪些字段具有值。使用 Phanton-dsl 1.5 我有类似的东西;
import com.websudos.phantom.query.{ AssignmentsQuery => AQ }
override def updateModel(m: Upd)(implicit ec: EC): Future[Unit] = {
if (m.isEmpty) return Future.successful(())
val upd = update
upd.where(_.user_id eqs m.user_id)
val mod: AQ[CTable, Val] = new AQ(this, upd.qb.`with`())
for (first_name <- m.first_name) mod.and(_.first_name setTo first_name)
for (last_name <- m.last_name) mod.and(_.last_name setTo last_name)
mod.future.map(_ => ())
}
现在我正在尝试迁移到最新版本的 Phantom-dsl (1.27),但我在仅使用 dsl 进行等效操作时遇到了问题。由于任何字段都可能是 None,因此构造第一个 modify() 然后使用任意数量的 and() 进行构造被证明是困难的。
任何有关如何处理此问题的建议都会有所帮助。
这可以使用 setIfDefined
实现,您不需要包装任何东西。
db.table.update.where(_.bla eqs bla)
.modify(_.x setIfDefined None)
.and(_.y setIfDefined Some("text")
这将基本上忽略所有 None
的内容,并强制它们不显示在查询中。
我的模型有一个更新方法,它采用带有选项类型的 class,我想构建一个更新语句,其中包含一个动态 SET,具体取决于哪些字段具有值。使用 Phanton-dsl 1.5 我有类似的东西;
import com.websudos.phantom.query.{ AssignmentsQuery => AQ }
override def updateModel(m: Upd)(implicit ec: EC): Future[Unit] = {
if (m.isEmpty) return Future.successful(())
val upd = update
upd.where(_.user_id eqs m.user_id)
val mod: AQ[CTable, Val] = new AQ(this, upd.qb.`with`())
for (first_name <- m.first_name) mod.and(_.first_name setTo first_name)
for (last_name <- m.last_name) mod.and(_.last_name setTo last_name)
mod.future.map(_ => ())
}
现在我正在尝试迁移到最新版本的 Phantom-dsl (1.27),但我在仅使用 dsl 进行等效操作时遇到了问题。由于任何字段都可能是 None,因此构造第一个 modify() 然后使用任意数量的 and() 进行构造被证明是困难的。
任何有关如何处理此问题的建议都会有所帮助。
这可以使用 setIfDefined
实现,您不需要包装任何东西。
db.table.update.where(_.bla eqs bla)
.modify(_.x setIfDefined None)
.and(_.y setIfDefined Some("text")
这将基本上忽略所有 None
的内容,并强制它们不显示在查询中。