我有一个便笺模型,我想附加到其他两个模型之一(客户和供应商)中。

在我的数据库中,我有一个foreignType和foreignId字段,用于保存类型或客户或供应商的相应ID,例如

notes: { {id: 1, body:'bar',foreignType:'customer',foreignId:100},
         {id: 2, body:'foo',foreignType:'supplier',foreignId:100}
       }

即,可以将票据附于客户或供应商。

惯例似乎是将该字段称为noteType?
我已经看到了tutorial,其中相关类型嵌套在JSON中,而不是嵌套在根目录中。

我的 Ember 模型如下所示:
//pods/note/model.js
  export default DS.Model.extend({
    //...
    body: DS.attr('string'),
    foreign: DS.belongsTo('noteable',{polymorphic:true})
  });

//pods/noteable/model.js (is there a better/conventional place to put this file?)
  export default DS.Model.extend({
    notes: DS.hasMany('note')
  });

//pods/customer/model.js
  import Noteable from '../noteable/model';

  export default Noteable.extend({ //derived from Noteable class
     name: DS.attr('string'),
     //...
   });

//pods/supplier/model.js
  // similar to customer



// sample incoming JSON
//
{"customer":{"id":2,"name":"Foobar INC",...},
 "contacts":
    [{"id":1757,"foreignType": "customer","foreignId":2,...},
     {"id":1753,"foreignType": "customer","foreignId":2,...},
     ...],
   ...
  "todos":
     [{"id":1,"foreignType":"customer","foreignId":2,"description":"test todo"}],
  "notes":
     [{"id":1,"foreignType":"customer","foreignId":2,"body":"Some customer note "}]
}

如何正确设置,即Ember期望什么?

我的注释未正确附加到客户模型上。它们显示在Ember Inspector的“数据”选项卡中,但是任何客户的注释列表为空。

我可以看到几种可能性:
  • 从DS.Model扩展了客户/供应商,并具有notes: belongsTo('noteable')属性,这意味着notes中的belongsTo不是多态的,因为不会有任何派生类,只有Noteable本身。不知道ember(数据)是否可以正确处理此嵌套。
  • 从Noteable扩展。如果我想要其他与客户或供应商相关的信息,例如地址或联系人,该怎么办?
  • 创建重复的模型,例如客户注释/供应商注释,客户联系人/供应商联系人,客户/供应商/员工地址。并让后端根据端点返回过滤的表/模型名称。我不喜欢重复自己....

  • Ember :2.2.0
    Ember 数据:2.2.1

    最佳答案

    我喜欢Ember Doc在这里如何解释多态-https://guides.emberjs.com/v2.13.0/models/relationships/#toc_polymorphism

    因此,首先您需要有一个“类型”,它将定义要使用的模型(您的数据称其为foreignType)

    接下来,您的笔记模型将是多态模型(类似于上面示例中的paymentMethod模型)。如果需要进一步说明,请在评论中告诉我,但是我认为,如果按照给定的示例进行操作,将非常清楚。

    07-24 18:07
    查看更多