2

查看 Ember 页面上的指南,我无法弄清楚如何在一对多的关系中连接模型。

App.Post = DS.Model.extend({
  comments: DS.hasMany('comment')
});

App.Comment = DS.Model.extend({
  post: DS.belongsTo('post')
});

1. 如何定义夹具?A 或 B 或其他

A)每个帖子“对象”中的评论

App.Post.FIXTURES = [
{
  id:1,
  title:"hello world",
  body:"hey ho",
  comments:[
   {
    text: "Very nice"
   },
   {
    text: "Very nice indeed"
   },
  ]
},
{
  id:2,
  title:"hello again",
  body:"I'm Bob",
  comments:[{
   text: "Pretty cool actually"
  }]
}
]

B)单独评论并与ID链接到帖子

App.Post.FIXTURES = [
{
  id:1,
  title:"hello world",
  body:"hey ho"
},
{
  id:2,
  title:"hello again",
  body:"I'm Bob"
}
]

App.Comment.FIXTURES = [
{
  post_id:1,
  text: "Very nice"
},
{
  post_id:1,
  text: "Very nice indeed"
},
{
  post_id:2,
  text: "Pretty cool actually"
}
]

2.关于从服务器获取

A)我是否需要单独加载帖子和评论,或者一次调用全部加载,使其结构类似于 1A 案例?

B)如果我想单独加载它们怎么办,例如等待用户单击确定评论链接,除非用户请求,否则无需为页面上的每个博客帖子下载 1000 条评论。

您能否提供一个简单版本的每个调用的样子?

4

1 回答 1

4

1. 如何定义夹具?别的东西。

正确的形式是仅将 id 作为comments属性嵌入到post.

App.Post.FIXTURES = [
{
  id:1,
  title:"hello world",
  body:"hey ho",
  comments : [1,2]
},
{
  id:2,
  title:"hello again",
  body:"I'm Bob",
  comments : [3]
}
]

App.Comment.FIXTURES = [
{
  id : 1,
  text: "Very nice"
},
{
  id : 2,
  text: "Very nice indeed"
},
{
  id : 3,
  text: "Pretty cool actually"
}
]

2. 从服务器获取

有几种方法可以解决这个问题。

使用“侧面加载”。您仍然提供评论 ID 列表作为comments属性,但您还在 JSON 响应中包含评论列表。

{posts:[

    {
      id:1,
      title:"hello world",
      body:"hey ho",
      comments : [1,2]
    },
    {
      id:2,
      title:"hello again",
      body:"I'm Bob",
      comments : [3]
    }
],
comments : [
    {
      id : 1,
      text: "Very nice"
    },
    {
      id : 2,
      text: "Very nice indeed"
    },
    {
      id : 3,
      text: "Pretty cool actually"
    }
]}

async在你的上使用hasMany以允许 Ember 在帖子已加载后查找评论。

App.Post = DS.Model.extend({
  comments: DS.hasMany('comment',{async:true})
});

如果您有数千条记录,则上述解决方案不会很好。而不是一次加载所有评论(使用侧面加载或async),您将希望使用分页一次仅加载几条评论。在这种情况下,您的PostRouteandPostController可能看起来像这样。

App.PostController = Ember.ObjetController.extend({
  needs : ['comments']
});

App.PostRoute = Ember.Route.extend({
  setupController : function(controller,model){
    this._super(controller,model);
    comments = this.store.find('comment',{post_id : model.get('id'), page : 1});
    this.controllerFor('comments').set('content',comments);
  }
});
于 2013-09-22T01:16:18.930 回答