【发布时间】:2021-05-26 06:59:04
【问题描述】:
我正在尝试从一个 API 调用中侧载关系数据。我的两个模型设置如下:
竞赛模型(child,belongsTo):
import Model, { attr, belongsTo } from '@ember-data/model';
export default class ContestModel extends Model {
@attr('date') createdAt;
@attr('string') description;
@belongsTo('brand', { inverse: 'contests' }) brand;
}
品牌模型(父级,hasMany):
import Model, { attr, hasMany } from '@ember-data/model';
export default class BrandModel extends Model {
@attr('date') createdAt;
@attr('string') name;
@hasMany('contest') contests;
}
我正在通过这条线获取:
this.store.findRecord('contest', params.contest_id, { include: 'brand' });
这是返回的 API 负载:
{
"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" // not sure what this does
},
"data": { "type": "brand", "id": 2 }
}
},
"links": {
"self": "http://example.com/contests/2" // not sure how this is useful
},
"included": [
{
"id": 2,
"type": "brand",
"attributes": {
"created_at": "2021-05-23 20:00:00 -0700",
"name": "aloha vibe"
}
}
]
}
}
这里的问题是调用myContest.brand 会返回一个代理对象,就像在这个SO post 中一样。
我的 API 有效负载是否不正确或者我的模型配置错误?或者是其他东西?我在Ember 3.25.3
来自 cmets 的更新:当我将 async: false 添加到 Ember 数据查询时,由于 toReturn.isEmpty 为真,我在 https://github.com/emberjs/data/blob/v3.25.0/packages/store/addon/-private/system/model/internal-model.ts#L705 这一行之后出现错误。我没有配置我的 API 有效负载吗?不知道出了什么问题。似乎createdAt 和name 都没有填充。
【问题讨论】:
-
myContest.brand应该是一个代理。由于记录已经在商店中,您应该能够访问它的 ID (myContest.brand.id) 或它的任何属性 (myContest.brand.name)。 -
你可以声明
async: false -
如果不进行第二次 API 调用,我将无法调用
myContest.brand.id -
我添加了
async: false,现在它显示:Uncaught Error: Assertion Failed: You looked up the 'brand' relationship on a 'contest' with id 1 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 (`belongsTo({ async: true })`) -
我用屏幕截图和导致异常的违规代码行更新了我的问题。将继续挖掘,但绝对欢迎任何想法!
标签: javascript ember.js ember-data json-api