Realm框架中如何让其他模型继承基础模型的公共字段?
解决Realm模型公共字段复用的问题
我明白你想让所有Realm模型共享Base里的uuid、created_by这类公共字段的需求,Realm确实没有原生支持通过类继承直接复用schema属性,但我们可以用以下两种简洁的方式实现:
方法1:手动合并Schema属性
先把公共字段抽成单独的对象,然后在子模型的schema里用对象展开运算符(或者Object.assign)合并公共属性和自定义属性:
// 定义公共字段集合 const baseProperties = { uuid: { type: 'string', optional: false }, created_by: { type: 'string', optional: false }, }; // 基础模型(如果不需要单独实例化Base,其实可以只保留公共字段对象) class Base { } Base.schema = { name: 'Base', properties: baseProperties }; // Student模型:合并公共字段与自定义字段 class Student { } Student.schema = { name: 'Student', properties: { ...baseProperties, // 展开公共字段 name: { type: 'string', optional: false }, age: { type: 'int', optional: true } // 其他自定义字段... } };
方法2:封装工具函数自动生成Schema
如果有很多模型需要复用公共字段,写一个工具函数来统一处理会更高效,避免重复代码:
// 公共字段 const baseProperties = { uuid: { type: 'string', optional: false }, created_by: { type: 'string', optional: false }, }; // 生成带公共字段的Schema的工具函数 function createModelSchema(modelName, customProperties) { return { name: modelName, properties: { ...baseProperties, ...customProperties } }; } // 定义Base模型 class Base { } Base.schema = createModelSchema('Base', {}); // 定义Student模型 class Student { } Student.schema = createModelSchema('Student', { name: { type: 'string', optional: false }, age: { type: 'int', optional: true } // 其他自定义字段... });
效果验证
这样定义后,当你创建Student实例时,就会自动包含uuid、created_by以及自定义的name、age字段,完全符合你预期的结构:
// 示例Student实例 const student = { uuid: 'xxx-xxx-xxx-xxx-xxx', created_by: 'xxx-xxx-xxx-xxx-xxx', name: 'Smith', age: 20 };
这种方式既满足了字段复用的需求,又符合Realm的schema定义规则,比尝试类继承更可靠。
内容的提问来源于stack exchange,提问作者A Rahman
相关产品推荐
相关产品推荐

