简体   繁体   English

ember-data:以hasMany关系加载记录

[英]ember-data: loading records in hasMany relationship

I am trying to code feature that allows logged-in users to add products to a "saved item" list. 我正在尝试对允许登录用户将产品添加到“保存的物品”列表中的功能进行编码。 The model is: 该模型是:

//saveditem.js model
export default DS.Model.extend({
    user: belongsTo('user'),
    product: belongsTo('product', { async: true }),
    dateAdded: attr('string')
});

On the saveditems route where the saved items are displayed, the model() hook is: 在显示已保存项目的saveditems路线上, model()挂钩为:

model() {
    return this.get("store").findAll('saveditem');
}

the api is returning records with JUST the ids: api返回带有ID的记录:

{
    "dateAdded": "Mon, 11 Dec 2017 20:59:10 GMT",
    "id": 4458,
    "product": 4458,
    "user": "me"
},
{
    "dateAdded": "Sun, 10 Dec 2017 10:26:02 GMT",
    "id": 3657,
    "product": 3657,
    "user": "me"
}
...

How can I get the hasMany relationship to load the actual products, using the IDs? 如何使用ID获得hasMany关系以加载实际产品?

I figured it out (prompted by arne.b's question). 我知道了(arne.b的问题提示)。 The setup was correct, but the way I was calling the items wasn't. 设置是正确的,但是我打电话的方式不正确。

I was doing this in the template: 我在模板中这样做:

{{#each model as |result|}}
    <div>
    {{result.productName}}
    </div>
{{/each}}

Which printed empty divs because it's looping through my saveditem records, but the relationship wasn't resolving because I wasn't calling the product object itself. 哪个打印了空的div,因为它正在遍历我saveditem记录,但是由于我没有调用product对象本身,所以关系无法解决。 The correct way: 正确的方法:

{{#each model as |result|}}
    <div>
    {{result.product.productName}}
    </div>
{{/each}}

I also needed to set async: true on the model: 我还需要在模型上设置async: true

export default DS.Model.extend({

    user: belongsTo('user'),
    product: belongsTo('product', { async: true }),
    dateAdded: attr('string')

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM