Vapor/Fluent:当模式中有uid数组时,子对象不保存



我有一个包含Coin实体和相应的Fluent Model的表。它拒绝保存,直到我删除了一个字段,该字段旨在包含一个uid数组。这被称为sources,它的功能是提供一个回溯到其他硬币的线索,从这些硬币中派生出一个新硬币——例如,如果用户有两个硬币(可以有任意的数值),目标是能够将它们合并成一个具有合并硬币组合值的硬币。

模式(带注释字段)看起来是这样的(它包括迁移,也带相应的字段注释掉):

final class Coin : Model, Content, ResponseEncodable {

init() {}

init(player: User, quantity: Int, type: CreatedFor, sources : [Coin] = []) {
self.id = id
self.$player.id = player.id!
self.quantity = quantity
self.type = type
//        self.sources = sources
}

static let schema: String = "coins"

@ID(key: .id)                   var id: UUID?

@Timestamp(key: "created_at", on: .create) var createdAt: Date?
@Timestamp(key: "updated_at", on: .update) var updatedAt: Date?

@Parent(key: "player")          var player: User

@Field(key: "quantity")         var quantity: Int
@Field(key: "type")             var type: CreatedFor
//    @Field(key: "sources")          var sources: [Coin]

enum CreatedFor: String, Codable {
case transfer
case ante
case purchase
case winnings
case gift
case merge
}
}
extension Coin {
struct BuildCoin: Fluent.Migration {
var name : String { "BuildCoin" }

func prepare(on database: Database) -> EventLoopFuture<Void> {
database.schema("coins")
.id()
.field("created_at", .datetime)
.field("updated_at", .datetime)
.field("player", .uuid, .required)
.field("quantity", .int, .required, .custom("DEFAULT 0"))
.field("type", .string, .required, .custom("DEFAULT 'gift'"))
//                .field("sources", .array(of: .uuid))
.create()
}

func revert(on database: Database) -> EventLoopFuture<Void> {
database.schema("coins").delete()
}

}
}

一旦我把它浓缩到出现问题的地方,我就能得到这个错误,这似乎来自postgres:

{"error":true,"reason":"server: column "sources" is of type uuid[] but expression is of type jsonb[] (transformAssignedExpr)"}

我想包括这个字段(但我现在可以继续没有它)。这里发生了什么?在调用init()时,它只是作为一个空数组被调用,所以我本以为这不会引起任何问题…

Thanks in advance…

如果你想保存为uid数组而不是

@Field(key: "sources") var sources: [Coin]

你应该使用

@Field(key: "sources") var sources: [UUID]

其他你试图保存硬币数组到DB,这个数组将被序列化到jsonb -因为它是对象而不是UUID。看看你的代码,我认为你应该使用1对多或多对多关系。

最新更新