Node.js sequelize embed hasMany IDs

≯℡__Kan透↙ 提交于 2019-12-23 15:09:53

问题


I am experimenting with a Ember app using ember-data and a node.js backend serving data from MySQL using Sequelize.js.

My problem: If I have a Comment model associated to a Post model through hasMany the expected JSON by ember-data looks like

{
  "post": {
    "comment_ids": [1, 2, 3]
  }
}

What would be the best way to query / generate this JSON without expensive loops etc. using sequelize?

The Comment model has a foreign key with the post_id.


回答1:


I went for implementing it like:

// include comments
Post.all({
  where: "..",
  include: [Comment]
}).success(function(posts) {
  // collect IDs
  _.each(posts, function(element) {
    element["comments"] = _.pluck(element.comments, 'id');
  });
});



回答2:


I'd suggest passing the buck to the client. You can set up a custom serializer client side that reformats the data into the expected format for ED. Additionally ED is expecting it in this format:

{
   "post": {
     "comments": [1, 2, 3]
   }
}

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

or if you choose to include the comments in the response

{
 "post": {
   "id": 1
   "title": "Rails is omakase",
   "comments": ["1", "2"],
   "_links": {
      "user": "/people/dhh"
   },
 },

 "comments": [{
   "id": "1",
   "body": "Rails is unagi"
  }, {
   "id": "2",
   "body": "Omakase O_o"
  }]
}

You can read more about it here: https://github.com/emberjs/data/blob/master/TRANSITION.md

At some point, someone is going to have to loop (or iterate) and it isn't an uncommon practice to iterate through your result set to build up your response (or serialize your response client side).



来源:https://stackoverflow.com/questions/20017334/node-js-sequelize-embed-hasmany-ids

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