Swift GRDB: 绑定主键并实现自增功能
Swift GRDB: 绑定主键并实现自增功能
在 Swift GRDB 中,要绑定主键并实现自增功能,需要按照以下步骤操作:
- 在模型类中,定义一个自增的主键属性,例如:
class User: Codable, FetchableRecord, MutablePersistableRecord {
var id: Int64?
var name: String
var email: String
static let databaseTableName = "users"
static let id = Column("id")
init(id: Int64? = nil, name: String, email: String) {
self.id = id
self.name = name
self.email = email
}
}
- 在数据库迁移中,使用
ColumnDefinition.autoincremented()方法为自增主键指定属性:
migrations.add(migration: "createUsersTable") { db in
try db.create(table: User.databaseTableName) { t in
t.column(User.id, .integer).primaryKey().autoincremented()
t.column(User.name, .text).notNull()
t.column(User.email, .text).notNull().unique()
}
}
- 现在可以使用
insert方法来将模型对象插入数据库,自增主键会自动分配一个新值:
try dbQueue.write { db in
var user = User(name: "Alice", email: "alice@example.com")
try user.insert(db) // user.id is now set to 1
user = User(name: "Bob", email: "bob@example.com")
try user.insert(db) // user.id is now set to 2
}
注意,如果在模型对象中手动设置了主键属性的值,那么自增主键将不会生效。
原文地址: https://www.cveoy.top/t/topic/oR9a 著作权归作者所有。请勿转载和采集!