Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

ember.js - Get belongsTo ID without fetching record

I'm trying to fetch the belongsTo ID without fetching the actual record. My JSON API returns the ID for the belongsTo relation.

I have the following models

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()
)

This is my route:

App.RecipeIndexRoute = Ember.Route.extend(
  model: (args) ->
    @store.find('recipe', args.recipe_id)
)

This is my controller:

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
        )

My JSON looks like this:

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
    }
  ]
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

See http://emberjs.com/blog/2016/05/03/ember-data-2-5-released.html#toc_code-ds-references-code


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...