[英]Ember-data 2: How to retrieve belongsTo model id without store fetching the record from the server
[英]Get belongsTo ID without fetching record
我正在嘗試獲取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.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。
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 GET:/ api / v1 / recipes / 1
{
"recipe": {
"id":1,
"title":"Recipe 1",
"ingredients":[2,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功能可以更輕松。 你現在可以這樣做:
var authorId = post.belongsTo("author").id();
見http://emberjs.com/blog/2016/05/03/ember-data-2-5-released.html#toc_code-ds-references-code
大量的工作是重做關系,你可以從數據屬性model.get('data.product.id')
它從基礎屬性中拉出來
對於ED 2.x,關系已經過重新設計,並且在獲取基礎數據之前已被破壞, 直到ds-references
功能着陸為止 。
要在ED belongsTo
執行此操作,您需要使用新的belongsTo
方法來處理基礎數據。
要獲取belongsTo ref的id:
var id = this.get('model').belongsTo('myBelongsToKey').value();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.