gpt4 book ai didi

ember.js - Ember 2 简单的多态关系

转载 作者:行者123 更新时间:2023-12-02 22:08:20 24 4
gpt4 key购买 nike

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

在我的数据库中,我有一个 foreignTypeforeignId 字段,用于保存客户或供应商的类型和相应的 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 检查器的“数据”选项卡中,但任何客户的注释列表都是空的。

我可以看到几种可能性:

  • DS.Model扩展客户/供应商,并拥有属性notes:belongsTo('noteable'),这意味着notes中的belongsTo不是' t 是多态的,因为不会有任何派生类,只有 Noteable 本身。不确定ember(数据)是否可以正确处理这种嵌套。

  • 值得注意延伸。如果我想要其他与客户或供应商相关的信息(例如地址或联系人)怎么办?

  • 创建重复模型,例如 customernote/suppliernote、customercontact/suppliercontact、客户/供应商/员工地址。并让后端根据端点返回过滤后的表/模型名称。不过我不喜欢重复自己的话......

Ember :2.2.0
Ember 数据:2.2.1

最佳答案

我喜欢 Ember 文档在这里解释多态性的方式 - https://guides.emberjs.com/v2.13.0/models/relationships/#toc_polymorphism

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

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

关于ember.js - Ember 2 简单的多态关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35044039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com