Ember.js 获取belongstoid而不获取记录
我试图在不获取实际记录的情况下获取belongsTo ID。我的JSON API返回belongsTo关系的ID 我有以下型号Ember.js 获取belongstoid而不获取记录,ember.js,ember-data,Ember.js,Ember Data,我试图在不获取实际记录的情况下获取belongsTo ID。我的JSON API返回belongsTo关系的ID 我有以下型号 App.Recipe = DS.Model.extend( title: DS.attr() ingredients: DS.hasMany('ingredient', async: true) ) App.Ingredient = DS.Model.extend( recipe: DS.belongsTo('recipe') product: DS.
App.Recipe = DS.Model.extend(
title: DS.attr()
ingredients: DS.hasMany('ingredient', async: true)
)
App.Ingredient = DS.Model.extend(
recipe: DS.belongsTo('recipe')
product: DS.belongsTo('product', async: true)
)
App.Product = DS.Model.extend(
title: DS.attr()
)
这是我的路线:
App.RecipeIndexRoute = Ember.Route.extend(
model: (args) ->
@store.find('recipe', args.recipe_id)
)
这是我的控制器:
App.RecipeIndexRoute = Ember.Route.extend(
model: (args) ->
@store.find('recipe', args.recipe_id)
)
我正在尝试在此控制器中查找产品id
App.RecipeIndexController = Ember.ObjectController.extend(
hasRecipeInCart: null
actions:
toggleCart: ->
@content.get('ingredients').then((ingredients) =>
# how do I get product id here, without lookup up the product relation?
# this 'get' makes Ember call: /api/v1/products/1
# I simply want the product ID (in this case 1), without having to call the server again.
ingredient.get('product').then((product) =>
product.id # => 1
)
我的JSON如下所示:
App.RecipeIndexRoute = Ember.Route.extend(
model: (args) ->
@store.find('recipe', args.recipe_id)
)
HTTP GET:/api/v1/recipes/1
{
"recipe": {
"id":1,
"title":"Recipe 1",
"ingredients":[2,1]
}
}
HTTP GET:/api/v1/Components?ids[]=2&ids[]=1
{
"ingredients": [
{
"id":2,
"recipe":1,
"product":1
},
{
"id":1,
"recipe":1,
"product":2
}
]
}
重做关系需要大量的工作,您可以从数据属性
model.get('data.product.id')
示例:对于ED 2.x,关系已被重新处理,并因获取基础数据而中断 要在ED 2.4+中执行此操作,您需要使用新的
belongsTo
方法来处理底层数据
要获取belongsTo ref的id,请执行以下操作:
var id = this.get('model').belongsTo('myBelongsToKey').value();
使用添加到余烬数据中的ds参考特性,这一点现在容易多了。您现在可以执行以下操作:
var authorId = post.belongsTo("author").id();
由于某种原因,请参见,它也会触发对服务器的调用:/api/v1/products/1。我使用了以下代码:@content.get('components')。然后((components)=>components.forEach((component,index,enumerable)=>productId=component.toJSON().product#这一行触发对服务器的调用。这在ED中是一个糟糕的实现,我可能需要做一个PR,或者找出它获取json模型的原因。可以像这样获取产品id:component.get('data')).product.id或component.\u data.product.id此选项在余烬2中不再有效。如何在不获取更新版本余烬(和余烬数据)中的记录的情况下获取belongsTo id?现在有一个更简单的解决方案:您可以执行以下操作:var authorId=post.belongsTo(“author”).id();ds引用已登陆:)如果要在模板中获取id,需要编写自己的帮助程序: