在不获取记录的情况下获取belongsTo ID [英] Get belongsTo ID without fetching record
问题描述
我试图在不获取实际记录的情况下获取belongsTo ID.我的 JSON API 返回belongsTo 关系的ID.
I'm trying to fetch the belongsTo ID without fetching the actual record. My JSON API returns the ID for the belongsTo relation.
我有以下型号
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)
)
这是我的控制器:
我正在尝试在此控制器中查找产品 ID.
I'm trying to find the product id within this controller.
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 如下所示:
HTTP 获取:/api/v1/recipes/1
HTTP GET: /api/v1/recipes/1
{
"recipe": {
"id":1,
"title":"Recipe 1",
"ingredients":[2,1]
}
}
HTTP GET:/api/v1/ingredients?ids[]=2&ids[]=1
HTTP GET: /api/v1/ingredients?ids[]=2&ids[]=1
{
"ingredients": [
{
"id":2,
"recipe":1,
"product":1
},
{
"id":1,
"recipe":1,
"product":2
}
]
}
推荐答案
现在通过添加到 ember 数据的 ds-reference 功能,这变得更加容易.你现在可以这样做:
This is now much easier with the ds-reference feature that was added to ember data. You can now do:
var authorId = post.belongsTo("author").id();
参见 http://emberjs.com/blog/2016/05/03/ember-data-2-5-released.html#toc_code-ds-references-code
这篇关于在不获取记录的情况下获取belongsTo ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!