Loading relationship model in Ember data

三世轮回 提交于 2019-12-25 00:14:11

问题


I have certain doubts with respect to Ember Data. I have a post and comments model.

//post.js
comments: DS.hasMany('comment')

//blog.js
post: DS.belongsTo('post')

I can create a comment for a particular "post" using

let blogPost = this.get('store').findRecord('post', 1);
let comment = this.get('store').createRecord('comment', {
   post: blogPost
});

But how can i fetch all the comments for a particular post? Like, I have multiple posts which has many comments and i want all the comments for a particular post id, say posts/id/comments

What is the right way to fetch the comments for a particular post id from the store and server?

The server response i get is only the id's of the comments while "findRecord"ing a post. I am following the REST API format and using REST Adapter and REST serializer for customizations.

Thanks in advance.


回答1:


There are a many ways to get these records loaded into the store. How you choose to do it depends on how the back end is set up. The easiest options are using the child records in a template, or doing a query. The instructions below only apply to apps using a REST adapter (since JSONAPI requests are standardized).

Let's start with using the records in a template.

In the route, fetch the post and return it in the model hook:

// post.js route    
import Ember from 'ember';

export default Ember.Route.extend({
  model(params) {
    return this.store.findRecord('post', params.post_id)
  },
});

Pass the model and its child records to a component:

// post.hbs route template
{{some-component comments=model.comments}}

Then use the comments in that component:

{{#each comments as |comment|}}
   <p>{{comment.note}}<p>
{{/each}}

You should find that using the comments in a template triggers GET requests to the ids that came back with your initial post fetch, such as /comments/1, /comments/2, etc. In the component's actions, you can access the comments as this.get('comments')

Another option is to specify a query parameter to be received and processed by the back end.

// post.js route    
import Ember from 'ember';

export default Ember.Route.extend({
  model(params) {
    return this.store.query('comments', {post: params.post_id})
  },
});

The code above will make a GET request to /comments?post=1. The back end is responsible for filtering through the database and returning only the records that belong to the post. Since model is a collection of comments, you'd use the results of the above in a template like this:

{{#each model as |comment|}}
  <p>{{comment.note}}</p>
{{/each}}


来源:https://stackoverflow.com/questions/46255025/loading-relationship-model-in-ember-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!