【发布时间】:2020-02-19 08:52:45
【问题描述】:
我的tag 和payment 模型之间定义了多对多关系,如下所示。
//models/tag.js
import Model, { attr, hasMany } from '@ember-data/model';
export default Model.extend({
name: attr('string'),
backgroundColour: attr('string'),
textColour: attr('string'),
payments: hasMany('payment')
});
// models/payment.js
import Model, { attr, hasMany } from '@ember-data/model';
export default Model.extend({
date: attr('date'),
amount: attr('number'),
paymentId: attr('string'),
tags: hasMany('tag'),
});
默认情况下,当我向付款添加标签时,付款的id 用作关系的键。我的目标是让 Ember 数据使用 paymentId 属性作为这种关系的键。
下面的 sn-p 显示了我正在加载的数据的结构,其中一个标签引用了 paymentId 属性的付款。
// Example tag
{
"id": "25",
"name": "Groceries",
"backgroundColour": "31b04b",
"textColour": "ffffff",
"payments": ["20190121201902210"] // References paymentId rather than id
},
// Example payment
{
"id": "1"
"date": "2019-01-27T22:00:00.000Z",
"amount": 1644.44,
"paymentId": "20190121201902210",
"tags": ["25"]
}
我尝试如下自定义支付序列化程序,
// serializers/payment.js
import ApplicationSerializer from './application';
export default ApplicationSerializer.extend({
keyForRelationship(key, _relationship) {
if (key === 'payments') {
return 'paymentId';
}
},
});
但是,在加载模型时出现此错误:Assertion Failed: All elements of a hasMany relationship must be instances of Model, you passed [ "20190121201902210" ]。
如何让 Ember 数据在查找相关付款时使用 paymentId 而不是 id?
【问题讨论】:
标签: ember.js ember-data