【问题标题】:How to fetch nested collection in Backbone-Relational如何在 Backbone-Relational 中获取嵌套集合
【发布时间】:2013-04-10 23:10:54
【问题描述】:

我正在尝试获取具有嵌套客户端联系人(人员)的所有客户端。我在获取属于客户/公司的客户联系人集合时遇到了一些麻烦。如果我试图获得收藏,我什么也得不到。顺便说一句,我是骨干和相关东西的新手。

这是我在控制台运行的代码来显示我的问题。

c = new SpencerGrafica.Models.Client({id:1})
c.fetch()
c.toJSON()
Object {id: 1, name: "Name", contacts: Array[0], …}
c.get('contacts').toJSON()
[] # (There should be ONE result, as I set this relation in rails console)

如果我运行 c.get('contacts').fetch() 我会得到所有“客户联系人”,而不仅仅是那些相关的。可能是网址问题?我错过了什么......?

谢谢。

这是模型的代码:

client.js.coffee

class SpencerGrafica.Models.Client extends Backbone.RelationalModel
  paramRoot: 'client'
  urlRoot: 'clients'

  defaults:
    id: null
    name: null

  relations: [{
    type: Backbone.HasMany,
    key: 'contacts',
    relatedModel: 'SpencerGrafica.Models.ClientContact',
    collectionType: 'SpencerGrafica.Collections.ClientContactsCollection',
    autoFetch: true,
    reverseRelation: {
      key: 'client',
      keySource: 'client_id'
    }
  }] 

class SpencerGrafica.Collections.ClientsCollection extends Backbone.Collection
  model: SpencerGrafica.Models.Client
  url: '/clients'

ClientContact.js.coffee

class SpencerGrafica.Models.ClientContact extends Backbone.RelationalModel
  paramRoot: 'client_contact'
  urlRoot: 'client_contacts'

  defaults:
    name: null
    email: null
    phone: null

class SpencerGrafica.Collections.ClientContactsCollection extends Backbone.Collection
  model: SpencerGrafica.Models.ClientContact
  url: 'client_contacts'

【问题讨论】:

    标签: backbone.js backbone-relational


    【解决方案1】:

    我遇到了类似的问题,还没有得到答案。但我也许可以和你分享一些想法。

    我猜你的 json 结构是:

    /clients/: {id: 1, name: "Name"}
    /client_contacts/: [{id: 1, client: 1}, {id: 2, client: 1}]
    

    那么您需要将/clients/ 更改为{id: 1, name: "Name", contacts: [1, 2]} 以让骨干关系找出关系。

    另一个问题是你使用/client_contacts 作为ClientContactsCollection 的url,这就是你找回所有联系人的原因,因为/client_contacts 是对所有联系人的请求。 许多人想查看http://backbonerelational.org/#example-person了解详情。

    如果您不想在 /clients/ 中包含联系人 ID,那么我们将面临同样的问题:Backbone-relational hasmany best practices

    【讨论】:

    猜你喜欢
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    相关资源
    最近更新 更多