获取belongsTo ID而不获取记录

 春暖花开时的夜晚 发布于 2023-02-11 20:25

我正在尝试获取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
    }
  ]
}

ianpetzer.. 13

现在,使用添加到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

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有