在 Swift GRDB 中,我们可以通过在 Encodable 协议中实现 encode(to:) 方法来将对象编码成数据库行。要绑定 primaryKey,可以在 encode(to:) 方法中手动将对象的 primaryKey 属性添加到数据库行中。

例如,假设我们有一个 Person 对象,其中包含一个 id 属性作为 primaryKey:

struct Person: Codable, FetchableRecord, PersistableRecord {
    var id: Int64?
    var name: String
}

我们可以将 Person 对象编码成数据库行,并将 id 属性绑定为 primaryKey,如下所示:

extension Person {
    enum Columns {
        static let id = Column('id')
        static let name = Column('name')
    }
    
    func encode(to container: inout PersistenceContainer) {
        container[Columns.name] = name
        if let id = id {
            container[Columns.id] = id
            container.databaseKey = id
        }
    }
}

在这个例子中,我们首先将 name 属性添加到数据库容器中。然后,我们检查 id 属性是否存在,并将其添加到容器中。最后,我们将容器的 databaseKey 属性设置为 id,以将其绑定为 primaryKey。

现在,当我们将 Person 对象插入数据库时,Swift GRDB 将自动将 id 属性绑定为 primaryKey:

let person = Person(id: nil, name: 'John')
try dbQueue.write { db in
    try person.insert(db)
}
Swift GRDB: 如何在 encode(to:) 方法中绑定 primaryKey

原文地址: https://www.cveoy.top/t/topic/oR94 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录