【问题标题】:Get belongsTo ID without fetching record获取belongsTo ID而不获取记录
【发布时间】:2013-12-27 01:37:01
【问题描述】:

我试图在不获取实际记录的情况下获取 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.js ember-data


    【解决方案1】:

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

    【讨论】:

    【解决方案2】:

    对于 ED 2.x,关系已被重新设计,并因获取基础数据而被破坏until the ds-references feature landed

    要在 ED 2.4+ 中执行此操作,您需要使用新的 belongsTo 方法来处理基础数据。

    要获取 belongsTo ref 的 id:

    var id = this.get('model').belongsTo('myBelongsToKey').value();
    

    【讨论】:

    【解决方案3】:

    重做关系需要做大量工作,您可以将其从数据属性 model.get('data.product.id') 的底层属性中提取出来

    示例:http://emberjs.jsbin.com/OxIDiVU/16/edit

    【讨论】:

    • 由于某种原因,这也会触发对服务器的调用:/api/v1/products/1。我使用了这段代码:@content.get('ingredients').then((ingredients) => ingredients.forEach((ingredient, index, enumerable) => productId = ingredients.toJSON().product # 这行触发调用到服务器。
    • 这是 ED 中一个丑陋的实现,我可能需要做 PR 或找出它为什么要为 json 获取模型。
    • 可以像这样获取产品 id:component.get('data').product.id 或 ingredients._data.product.id
    • 这在 Ember 2 中不再有效。如何在不获取较新版本的 Ember(和 Ember 数据)中的记录的情况下获取 belongsTo id?
    • 现在有一个更简单的解决方案:emberjs.com/blog/2016/05/03/… 你可以这样做:var authorId = post.belongsTo("author").id();
    猜你喜欢
    • 2010-10-03
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    • 2012-12-14
    相关资源
    最近更新 更多