从 ember JS 中的模型实例中查找关系的 class 名称
Find the class name of a relation from the instance of a model in ember JS
我有 foo
个 ember 数据模型的实例 thing
。 thing.js 有以下 属性 :
owner: DS.belongsTo('user')
如果我的 foo
的所有者为空,我如何才能仅使用 foo
和 'owner'
字符串来检索表示模型的值 'user'
所有者关系?
编辑:我想让我的 select-relation 组件处理名称不同于 class name
的关系
看来我可以做到以下几点:
this.get('model').get('_internalModel._relationships.initializedRelationships.'+this.get('relation')+'.relationshipMeta.type')
model
是一个实例,relation
关系名称的字符串,它正确地 return 关系的模型。
编辑:更好的解决方案,不使用来自 ember discord 的私有 API:
function getRelatedModelName(record, relationName){
let ParentModelClass = record.constructor;
let meta = get(ParentModelClass, 'relationshipsByName').get(relationName);
return meta.type;
}
听起来您还有一些工作要做才能完成建立您的人际关系。通读 this page 指南。
如果关系设置正确,要获得关联的用户,您应该可以做到foo.owner
。这假设用户已经出现在商店中。我建议使用 Ember Inspector 浏览器插件来调试关系。
这看起来像是 typeForRelationship 的用例。
在您的示例中,您应该能够执行类似
的操作
store.modelFor('thing').typeForRelationship('owner', store);
如果您不喜欢这种方法,可以使用 belongsTo reference API,您可以在其中使用关系中的元数据来获取类型
foo.belongsTo('owner').type
这种方法的唯一问题是 type
属性 可能不是 public API 并且可能(虽然不太可能)在某个时候改变。
我有 foo
个 ember 数据模型的实例 thing
。 thing.js 有以下 属性 :
owner: DS.belongsTo('user')
如果我的 foo
的所有者为空,我如何才能仅使用 foo
和 'owner'
字符串来检索表示模型的值 'user'
所有者关系?
编辑:我想让我的 select-relation 组件处理名称不同于 class name
的关系看来我可以做到以下几点:
this.get('model').get('_internalModel._relationships.initializedRelationships.'+this.get('relation')+'.relationshipMeta.type')
model
是一个实例,relation
关系名称的字符串,它正确地 return 关系的模型。
编辑:更好的解决方案,不使用来自 ember discord 的私有 API:
function getRelatedModelName(record, relationName){
let ParentModelClass = record.constructor;
let meta = get(ParentModelClass, 'relationshipsByName').get(relationName);
return meta.type;
}
听起来您还有一些工作要做才能完成建立您的人际关系。通读 this page 指南。
如果关系设置正确,要获得关联的用户,您应该可以做到foo.owner
。这假设用户已经出现在商店中。我建议使用 Ember Inspector 浏览器插件来调试关系。
这看起来像是 typeForRelationship 的用例。
在您的示例中,您应该能够执行类似
的操作store.modelFor('thing').typeForRelationship('owner', store);
如果您不喜欢这种方法,可以使用 belongsTo reference API,您可以在其中使用关系中的元数据来获取类型
foo.belongsTo('owner').type
这种方法的唯一问题是 type
属性 可能不是 public API 并且可能(虽然不太可能)在某个时候改变。