我们在这个项目中使用 JSONAPI,但由于 [原因] 我们无法在 API 中处理其推荐的关系结构,因此我们将它们作为嵌套对象提供并期待它们,格式如下:
{
"data":{
"type":"video",
"id":"55532284a1f9f909b0d11d73",
"attributes":{
"title":"Test",
"transcriptions":{
"type": "embedded",
"data":[
{
"type":"transcription",
"id":"203dee25-4431-42d1-a0ba-b26ea6938e75",
"attributes":{
"transcriptText":"Some transcription text here. And another sentence after it.",
"cuepoints":{
"type":"embedded",
"data":[
{
"type":"cuepoint",
"id":"bb6b0434-bdc4-43e4-8010-66bdef5c432a",
"attributes":{
"text":"Some transcription text here."
}
},
{
"type":"cuepoint",
"id":"b663ee00-0ebc-4cf4-96fc-04d904bc1baf",
"attributes":{
"text":"And another sentence after it."
}
}
]
}
}
}
]
}
}
}
}
我有以下模型结构:
// models/video
export default DS.Model.extend({
transcriptions: DS.hasMany('transcription')
)};
// models/transcription
export default DS.Model.extend({
video: DS.belongsTo('video'),
cuepoints: DS.hasMany('cuepoint')
});
// models/cuepoint
export default DS.Model.extend({
transcription: DS.belongsTo('transcription')
);
现在,我们要做的是保存一条video
记录,并让它序列化transcriptions
它所cuepoints
包含的内容。我有以下序列化程序,它可以很好地将 a 嵌入transcription
到video
ie 中。一个级别,但我也需要将其嵌入其中cuepoints
。
export default DS.JSONAPISerializer.extend({
serializeHasMany: function(record, json, relationship) {
var hasManyRecords, key;
key = relationship.key;
hasManyRecords = Ember.get(record, key);
if (hasManyRecords) {
json.attributes[key] = {};
hasManyRecords.forEach(function(item) {
json.attributes[key].data = json.attributes[key].data || [];
json.attributes[key].data.push({
attributes: item._attributes,
id: item.get('id'),
type: item.get('type')
});
});
} else {
this._super(record, json, relationship);
}
}
});
检查方法中的record
,json
和relationship
属性serializeHasMany
,我看不到任何有关嵌套关系的信息,所以甚至不确定我使用的是正确的方法。
有什么想法我会出错吗?