使用一个API调用检索ember数据关系

Retrieve ember data relationship with one API call

本文关键字:检索 调用 ember 数据 关系 API 一个      更新时间:2023-09-26

我有两个模型:

:

export default DS.Model.extend({
  name: DS.attr('string'),
  email: DS.attr('string'),
  messages: DS.hasMany('message'),
})

消息:

export default DS.Model.extend({

  message: DS.attr('string'),
  date: DS.attr('date'),
  ticket: DS.belongsTo('ticket', { async: true }),
});

和使用这种模型方法的路由器:

  model(params) {
   return this.get('store').findRecord('ticket', params.id,  {reload: true, include: 'messages'});
 },

在页面重新加载时,只调用tickets/:id,但有时会调用messages/:id。为什么不使用包含的数据并尝试从服务器检索?

我已经尝试了async: false上的hasMany关系,但我有这个错误:

Error: Assertion Failed: You looked up the 'messages' relationship on a 'ticket' with id 15 but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.hasMany({ async: true })`)

任何想法?

这是GET tickets/:id响应:

{"data":
{
"id":"15",
"type":"tickets",
"attributes":{...},
"relationships":{"messages":{"data":[{"id":"1478482584658","type":"messages"},{"id":"1478482588516","type":"messages"},{"id":"1478517720","type":"messages"},{"id":"1478517813","type":"messages"},{"id":"1478517893","type":"messages"},{"id":"1478530030","type":"messages"},{"id":"1478530032","type":"messages"},{"id":"1478533446","type":"messages"}]}}},
"included":[
{"id":"1478482584658","type":"messages","attributes":{...}},{"id":"1478482588516","type":"messages","attributes":{...}},
...
}
}
]
}

为什么不从included获取数据并对服务器进行其他调用?

承诺呢?

在处理关系时,重要的是要记住它们返回承诺。https://guides.emberjs.com/v2.1.0/models/working-with-relationships/toc_relationships-as-promises