Realm同类型双字段下如何设置backlink实现按条码查询商品?
一、现有Schema设计合理性评估
现有设计本身符合业务逻辑,核心优势如下:
- 清晰区分了商品基础单位与衍生单位的层级关系,将
SoldableUnit设置为嵌入对象(embedded: true)的设计也适配「单位属于商品固有属性、不会跨商品复用」的业务场景,不需要额外维护单位对象的独立生命周期。
但该设计存在一个局限:Realm 中的嵌入对象不支持反向链接(Backlink),因为嵌入对象完全依附于父对象存在,本身没有独立的全局标识,所以你之前想通过反向关联查询的思路无法落地。如果你的业务不存在多商品共用同一单位的需求,现有设计不需要调整,直接用原生查询语法即可实现需求。
二、按barcode查询Product的实现方案
不需要调整Schema的前提下,直接在Product集合上做多条件过滤即可,查询条件同时匹配baseUnit的barcode和derivedUnits中任意元素的barcode即可,示例代码如下:
// 输入的查询条码 const targetBarcode = 'xxxxxxx'; // 执行查询 const matchedProducts = realm.objects(Product.schemaName) .filtered('baseUnit.barcode == $0 OR ANY derivedUnits.barcode == $0', targetBarcode);
查询逻辑说明:
baseUnit.barcode == $0用于匹配基础单位的条码ANY derivedUnits.barcode == $0用于匹配任意衍生单位的条码- 你已经给
SoldableUnit的barcode字段添加了索引,该查询性能不会有明显问题。
可选Schema优化方案(适配单位可复用场景)
如果后续业务需要支持多个商品共用同一个销售单位,你可以将SoldableUnit改为非嵌入对象,增加主键,同时添加两个反向链接字段即可:
// 修改后的SoldableUnit schema public static schema: Realm.ObjectSchema = { name: SoldableUnit.schemaName, primaryKey: 'unitId', // 新增主键 // 移除embedded: true配置 properties: { unitId: {type: 'string'}, unitName: {type: 'string'}, sellingPrice: {type: 'double'}, weight: {type: 'float'}, barcode: {type: 'string', optional: true, indexed:true}, // 新增两个反向链接 baseUnitOf: {type: 'linkingObjects', objectType: Product.schemaName, property: 'baseUnit'}, derivedUnitOf: {type: 'linkingObjects', objectType: Product.schemaName, property: 'derivedUnits'} }, };
该场景下你可以先查询SoldableUnit匹配条码后,直接从baseUnitOf和derivedUnitOf中获取关联的商品:
const matchedUnit = realm.objects(SoldableUnit.schemaName) .filtered('barcode == $0', targetBarcode)[0]; const relatedProducts = [...matchedUnit.baseUnitOf, ...matchedUnit.derivedUnitOf];
内容的提问来源于stack exchange,提问作者xuantubka
相关产品推荐
相关产品推荐

