iOS Realm如何为Group添加维护人列表并反向查询Account维护的群组
结论
你的思路可行,只需要修正几个Realm模型的用法错误即可,具体实现如下:
核心修正点
- 你的
Group类没有继承Realm的Object基类,需要先补全继承关系,否则无法作为Realm持久化对象 - 对多的关联关系不要用Swift原生
Array(也就是你写的[Account?]),需要用Realm提供的List类型,Realm才会自动持久化关联关系 - 不需要可选类型
Account?,维护人必然是有效的Account对象,直接存非可选类型即可 - 要从
Account侧反向查询作为维护人的群组,新增LinkingObjects反向关联属性即可,和你现有的管理员反向查询逻辑一致 - 注意你拼写的
mantainers是错误的,正确拼写为maintainers,属性名和反向关联的查询参数必须完全一致,否则会查询失败
修正后的完整模型代码
class Account: Object { @Persisted(primaryKey: true) var _id: ObjectId = ObjectId.generate() @Persisted var name : String = "" // 作为管理员管理的群组 let adminGroups = LinkingObjects(fromType: Group.self, property: "administrator") // 作为维护人参与的群组 let maintainerGroups = LinkingObjects(fromType: Group.self, property: "maintainers") } class Group: Object { @Persisted var administrator: Account? // 维护人列表,用Realm的List类型存储对多关系 @Persisted var maintainers = List<Account>() }
常用操作示例
- 给群组新增维护人:
// 写入操作需要在Realm写事务内执行 try! realm.write { group.maintainers.append(accountA) group.maintainers.append(accountB) }
- 查询某账号作为维护人参与的所有群组:
let joinedGroups = account.maintainerGroups // 可直接加过滤条件,比如查群组名称带"项目"的维护群组 let filteredGroups = account.maintainerGroups.where { $0.name.contains("项目") }
- 权限判断示例:
enum PermissionLevel { case admin, maintainer, normal } func checkPermission(for account: Account, in group: Group) -> PermissionLevel { if group.administrator?._id == account._id { return .admin } else if group.maintainers.contains(account) { return .maintainer } else { return .normal } }
内容的提问来源于stack exchange,提问作者ppusiol
相关产品推荐
相关产品推荐

