Scala 过滤后但更新/从更新中排除字段之前实体中的平滑更新字段?
在下面的函数中,我正在更新一个用户。但用户有一个“createdDate”字段,该字段将位于数据库中,但不会位于客户端传递的用户实体中:Scala 过滤后但更新/从更新中排除字段之前实体中的平滑更新字段?,scala,playframework,slick,slick-3.0,Scala,Playframework,Slick,Slick 3.0,在下面的函数中,我正在更新一个用户。但用户有一个“createdDate”字段,该字段将位于数据库中,但不会位于客户端传递的用户实体中: def update(user: User): Future[Int] = { db.run( userTable .filter(_.userId === user.userId) // Can I set user.createdDate here to the existing value?
def update(user: User): Future[Int] = {
db.run(
userTable
.filter(_.userId === user.userId)
// Can I set user.createdDate here to the existing value?
.update(user)
)
}
在调用update(user)之前,是否可以使用数据库中现有用户行的值设置user.createdDate
以下是我在创建用户时如何设置createdDate字段的参考(用户是不可变的case类,因此我复制来设置createdDate):
您可以像这样分解用户对象并跳过
createdDate
userTable
.filter(_.id === id)
.map(t => (t.firstName,..., t.modifiedDate))
.update(("John",..., Some(Timestamp.valueOf(LocalDateTime.now))))
您可以像这样分解用户对象并跳过
createdDate
userTable
.filter(_.id === id)
.map(t => (t.firstName,..., t.modifiedDate))
.update(("John",..., Some(Timestamp.valueOf(LocalDateTime.now))))
我最后只是在更新前阅读,如下所示:
this.read(user.userId).flatMap {
case Some(existingUser) =>
db.run(
userTable.
filter(_.userId === user.userId).
update(user.copy(createdDate = existingUser.createdDate)))
case None => throw new NotFoundException(...)
}
我最后只是在更新前阅读,如下所示:
this.read(user.userId).flatMap {
case Some(existingUser) =>
db.run(
userTable.
filter(_.userId === user.userId).
update(user.copy(createdDate = existingUser.createdDate)))
case None => throw new NotFoundException(...)
}
谢谢,虽然我的用户类有很多字段,大约15个(在我的示例中没有显示),但是如果有很多字段,这可能会有点不方便?另外,如果一个字段在以后添加到用户中会怎样?您必须知道如何使用新字段更新此方法?您可以在User case类或其同伴中定义
updateFunction
内部map
。也许这有助于将它们保持在一起。谢谢,虽然我的用户类有很多字段,大约15个(在我的示例中没有显示),但是如果有很多字段,这可能有点不方便?另外,如果一个字段在以后添加到用户中会怎样?您必须知道如何使用新字段更新此方法?您可以在User case类或其同伴中定义updateFunction
内部map
。也许这有助于保持他们在一起。