我有一个名为 profile 的表,我的模型在这里:
final class Profile: Model, Content {
struct Keys {
static let userId: FieldKey = "user_id"
static let nickname: FieldKey = "nickname"
static let bio: FieldKey = "bio"
}
static let schema = "profile"
@ID(key: .id) var id: UUID?
@Field(key: Keys.nickname) var nickname: String?
@Field(key: Keys.bio) var bio: String?
@Parent(key: Keys.userId) var user: User
init() {}
init(id: UUID? = nil, nickname: String?, bio: String?, userId: User.IDValue) {
self.id = id
self.nickname = nickname
self.bio = bio
self.$user.id = userId
}
}
我从客户端收到了这样的请求正文内容:
{
"bio": "my new bio"
}
我想要的是客户端更新它传递的任何属性,我的代码可以做到这一点:
let userId = try req.auth.require(User.self).requireID()
guard let oldProfile = try await Profile.query(on: req.db).filter(\.$user.$id == userId).first() else {
let newProfile = Profile(nickname: edit.nickname, bio: edit.bio, userId: userId)
try await newProfile.save(on: req.db)
return GlobalResponse(code: .ok, msg: .custom("save success"))
}
if let b = edit.bio {
oldProfile.bio = b
}
if let n = edit.nickname {
oldProfile.nickname = n
}
try await oldProfile.update(on: req.db)
return GlobalResponse(code: .ok, msg: .custom("save success"))
这些代码工作正常,但是有没有更好或更简单的方法来做到这一点? 我没有找到一种简单的方法来完成更新插入工作。
我刚刚开始学习vapor。
我尝试在 Vapor Fluent 中找到一些 upsert 代码,但什么也没得到。
Fluent 目前不支持 upsert,主要是因为以通用方式在所有支持的数据库中支持它很复杂。
您可以下拉到 SQLKit 来执行更新插入,但是,这会很好地工作。