2017-10-15 98 views
0

我很努力地理解如何从两个相关模型中获取数据来显示。Ember:从模板访问多对多数据

我有一个食谱,可以有很多的标签,并且可以有许多食谱标签:

//models/recipe.js 
export default DS.Model.extend({ 
    name: DS.attr('string'), 
    tags: DS.hasMany('tag') 
}); 

//models/tag.js 
export default DS.Model.extend({ 
    name: DS.attr('string'), 
    tags: DS.hasMany('recipe') 
}); 

我想从我的食谱路线做这样的事情(通过一个组成部分):

//templates/components/list-recipes.hbs 
<ul> 
    {{#each recipes as |recipe|}} 
    <li>{{recipe.name}} - {{#each recipe.tags as |tag|}} {{tag}} {{/each}}</li> 
    {{/each}} 
</ul> 

//templates/recipes.hbs 
{{list-recipes recipes=model}} 

如果我输出{{ recipe.tags }},我得到一个<DS.PromiseManyArray>

我该如何解决这个承诺?

我尝试添加{include: tags}到我的食谱路线 - 但它似乎并没有有所作为:

//routes/recipes.js 
export default Route.extend({ 
    model() { 
    return this.get('store').findAll('recipe', {include: 'tags'}); 
    } 
}); 

我的数据:

enter image description here

在此先感谢

回答

0

外貌就像您在输出标签时缺少名称(即{{tag.name}}

这是否适合您?否则,你所拥有的一切看起来正确...

//templates/components/list-recipes.hbs 
<ul> 
    {{#each recipes as |recipe|}} 
    {{! line below updated slightly }} 
    <li>{{recipe.name}} - {{#each recipe.tags as |tag|}} {{tag.name}} {{/each}}</li> 
    {{/each}} 
</ul> 

此外,日后调试的目的,你也可以使用{{debugger}}{{log recipes}}追查什么错误

+0

不,不幸的是,这不是工作要么。另外,如果我输出'recipe.tags.length',我会得到0,尽管存在与配方相关的标签。 –

+0

是的,该数据信息是有帮助的。它看起来像你的后端没有发送标签信息作为标准的JSON:API对象,这将解释Ember Data的混乱。具体来说,你的标签是*嵌入*而不是*包含*。为了匹配JSON:API规范,您需要在每个食谱中有一个“关系”关键字,其中包含关于哪些标记与所涉及的配方链接的信息。如果你看一下这个主页上的例子:http://jsonapi.org/你需要匹配'relationships.data'方法。这有帮助吗? – acorncom