Ember 3.25 BelongsTo关联无法侧载加载问题排查
问题根源
你的问题核心是API返回的payload不符合JSON:API规范,其次存在模型配置的小疏漏,具体如下:
included数组层级错误
JSON:API规范要求侧载数据的included数组必须和顶层data字段平级,你当前的payload把included嵌套到了contest资源的data对象内部,导致Ember Data无法识别到侧载的Brand记录,自然无法正确填充关联关系,这也是你加async: false后报toReturn.isEmpty的直接原因。
修正后的payload结构示例:
{ "data": { "type": "contest", "id": 1, "attributes": { "body_json": [ { "question": "what time is it?", "answers": ["1PM", "2PM", "3PM", "4PM"] }, { "question": "which collection is this artwork from?", "answers": ["botanical garden collection", "ghibli collection", "adventure collection", "swag collection"] } ], "created_at": "2021-05-23 18:00:00 -0700", "description": "a good description goes here" }, "relationships": { "brand": { "links": { "self": "http://example.com/contests/2/relationships/brand" }, "data": { "type": "brand", "id": 2 } } }, "links": { "self": "http://example.com/contests/2" } }, "included": [ { "id": 2, "type": "brand", "attributes": { "created_at": "2021-05-23 20:00:00 -0700", "name": "aloha vibe" } } ] }
关联配置不匹配
你的Brand模型中hasMany配置缺少对应的inverse参数,和Contest模型的关联声明不匹配,修正后的Brand模型代码:
import Model, { attr, hasMany } from '@ember-data/model'; export default class BrandModel extends Model { @attr('date') createdAt; @attr('string') name; // 补充inverse参数对应Contest的brand关联 @hasMany('contest', { inverse: 'brand' }) contests; }
关联返回Proxy的正常逻辑说明
Ember Data的关联默认是async: true,js代码中直接访问myContest.brand返回的是PromiseProxy对象,需要通过await获取实际值:
const myContest = await this.store.findRecord('contest', params.contest_id, { include: 'brand' }); const brand = await myContest.brand; // 拿到真实的Brand实例
模板中直接使用{{myContest.brand.name}}会自动解包,不需要额外处理。
注:payload里的links字段是JSON:API规范的可选字段,仅用于标识资源访问地址,不会影响数据解析逻辑。
内容的提问来源于stack exchange,提问作者Sticky
相关产品推荐
相关产品推荐

