Realm关联已有标签创建人员文档报错,求正确关联方法
如何在Realm中将新创建的人员关联到已有标签?
你的代码报错是因为当你传入{ _id: ${org._id}-2021 }作为tags值时,Realm会尝试创建一个新的Tags对象,但该主键对应的标签已经存在,因此触发主键冲突错误。要实现关联已有标签,正确的做法是先从Realm中查询出目标标签的实例,再将这些实例赋值给People的tags属性。
修正后的代码示例
// 先通过主键查询已存在的标签实例 const targetTagId = `${org._id}-2021`; const existingTag = realm.objectForPrimaryKey<Tags>('tags', targetTagId); // 先判断标签是否存在,避免后续报错 if (!existingTag) { throw new Error(`标签 ${targetTagId} 不存在`); } // 在事务中创建人员并关联已有标签 const person = realm.write(() => { return new People(realm, { email, name, org_id: org._id, tags: [existingTag], // 传入已查询到的标签实例 }); });
关联多个已有标签的场景
如果需要给人员关联多个标签,只需批量查询出对应实例即可:
const tagIds = [`${org._id}-2021`, `${org._id}-2022`, `${org._id}-2023`]; // 查询所有存在的标签实例,过滤掉不存在的项 const existingTags = tagIds .map(tagId => realm.objectForPrimaryKey<Tags>('tags', tagId)) .filter(tag => tag !== null); const person = realm.write(() => { return new People(realm, { email, name, org_id: org._id, tags: existingTags, }); });
关键说明
- Realm的关系关联需要传入实际的Realm对象实例,而不是仅包含主键的普通JavaScript对象。
- 使用
realm.objectForPrimaryKey()是通过主键查询已有对象最直接的方式,也可以用realm.objects<Tags>('tags').filtered()进行更复杂的条件查询。
内容的提问来源于stack exchange,提问作者JoshJoe
相关产品推荐
相关产品推荐

