Sails.js填充嵌套协会 [英] Sails.js populate nested associations

查看:334
本文介绍了Sails.js填充嵌套协会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我自己关于Sails.js版本0.10 RC5关联的问题。我已经建立在多个模型关联到另一个应用程序,和我在一个点,我需要去鸟巢协会莫名其妙地到来了。

有三部分组成:

首先有类似博客文章,这是由一个用户编写。在博客文章我想告诉喜欢他们的用户名相关用户的信息。现在,这里的一切工作正常。直到下一个步骤:我想显示哪些与职位相关的评论

的意见是一个单独的模型,叫做评论。其中每一个还具有与之相关联的作者(用户)。我可以很容易地显示评论列表,虽然当我想以显示与注释相关联的用户的信息,我无法弄清楚如何填充与用户信息的注释。

在我的控制器我试图做这样的事情:

 发布
  .findOne(req.param(ID))
  .populate(用户)
  .populate(意见)//我想填充.populate(用户)或东西此评论
  .exec(函数(ERR,POST){
    //处理错误和放大器;渲染视图等。
  });

在我的帖子的'秀'动作我试图获取这样的信息(简体):

 < UL>
  <% - _.each(post.comments,功能(评论){%GT;
    <立GT;
      &所述;%= comment.user.name%GT;
      &所述;%= comment.description%GT;
    < /李>
  &所述;%}); %GT;
< / UL>

该comment.user.name会,虽然不确定。如果我尝试只访问'用户'属性,如comment.user,它会显示出它的ID。这告诉我,当我与另一个模型关联注释不是自动填充用户的信息的注释。

任何人的任何理想妥善解决这个问题:?)

在此先感谢!

P.S。

有关澄清,这是我如何初步建立了不同型号的关联:

  // user.js的
帖子:{
  收藏:后
},
小时: {
  集合:'小时'
},
注释: {
  收藏:评论
}// Post.js
用户:{
  型号:'用户'
},
注释: {
  收藏:评论,
  通过:后
}// Comment.js
用户:{
  型号:'用户'
},
岗位:{
  型号:后
}


解决方案

或者你可以使用内置的青鸟承诺功能来做到这一点。 (上Sails@v0.10.5工作)

请参阅下面的codeS:

VAR _ =要求('lodash');...岗位
  .findOne(req.param(ID))
  .populate(用户)
  .populate(意见)
  。然后(函数(岗位){
    VAR commentUsers = User.find({
        ID:_.pluck(post.comments,用户)
          //_.pluck:检索从post.comments集合中的所有元素的用户属性的值。
      })
      。然后(功能(commentUsers){
        返回commentUsers;
      });
    返回[后,commentUsers]
  })
  .S $ P $垫(函数(邮局,commentUsers){
    commentUsers = _.indexBy(commentUsers,ID);
    //_.indexBy:创建从通过给定的回调运行集合的每个元素的结果生成的键组成的对象。每个键对应的值是负责生成密钥的最后一个元素
    post.comments = _.map(post.comments,功能(评论){
      comment.user = commentUsers [comment.user]
      返回评论;
    });
    res.json(岗位);
  })
  .catch(功能(错误){
    返回res.serverError(ERR);
  });

一些解释:


  1. 我使用的是罗短跑来处理数组。有关详细信息,请参阅官方文件

  2. 请注意第一,那么功能里面的返回值,这些对象[帖子,commentUsers]阵内也承诺的对象。这意味着它们不包含值的数据时,他们首先被执行,直到他们得到的价值。让S $ P $垫功能将等待acture值来继续做剩下的东西。

I've got myself a question regarding associations in Sails.js version 0.10-rc5. I've been building an app in which multiple models are associated to one another, and I've arrived at a point where I need to get to nest associations somehow.

There's three parts:

First there's something like a blog post, that's being written by a user. In the blog post I want to show the associated user's information like their username. Now, everything works fine here. Until the next step: I'm trying to show comments which are associated with the post.

The comments are a separate Model, called Comment. Each of which also has an author (user) associated with it. I can easily show a list of the Comments, although when I want to display the User's information associated with the comment, I can't figure out how to populate the Comment with the user's information.

In my controller i'm trying to do something like this:

Post
  .findOne(req.param('id'))
  .populate('user')
  .populate('comments') // I want to populate this comment with .populate('user') or something
  .exec(function(err, post) {
    // Handle errors & render view etc.
  });

In my Post's 'show' action i'm trying to retrieve the information like this (simplified):

<ul> 
  <%- _.each(post.comments, function(comment) { %>
    <li>
      <%= comment.user.name %>
      <%= comment.description %>
    </li>
  <% }); %>
</ul>

The comment.user.name will be undefined though. If I try to just access the 'user' property, like comment.user, it'll show it's ID. Which tells me it's not automatically populating the user's information to the comment when I associate the comment with another model.

Anyone any ideals to solve this properly :)?

Thanks in advance!

P.S.

For clarification, this is how i've basically set up the associations in different models:

// User.js
posts: {
  collection: 'post'
},   
hours: {
  collection: 'hour'
},
comments: {
  collection: 'comment'
}

// Post.js
user: {
  model: 'user'
},
comments: {
  collection: 'comment',
  via: 'post'
}

// Comment.js
user: {
  model: 'user'
},
post: {
  model: 'post'
}

解决方案

Or you can use the built-in Blue Bird Promise feature to make it. (Working on Sails@v0.10.5)

See the codes below:

var _ = require('lodash');

...

Post
  .findOne(req.param('id'))
  .populate('user')
  .populate('comments')
  .then(function(post) {
    var commentUsers = User.find({
        id: _.pluck(post.comments, 'user')
          //_.pluck: Retrieves the value of a 'user' property from all elements in the post.comments collection.
      })
      .then(function(commentUsers) {
        return commentUsers;
      });
    return [post, commentUsers];
  })
  .spread(function(post, commentUsers) {
    commentUsers = _.indexBy(commentUsers, 'id');
    //_.indexBy: Creates an object composed of keys generated from the results of running each element of the collection through the given callback. The corresponding value of each key is the last element responsible for generating the key
    post.comments = _.map(post.comments, function(comment) {
      comment.user = commentUsers[comment.user];
      return comment;
    });
    res.json(post);
  })
  .catch(function(err) {
    return res.serverError(err);
  });

Some explanation:

  1. I'm using the Lo-Dash to deal with the arrays. For more details, please refer to the Official Doc
  2. Notice the return values inside the first "then" function, those objects "[post, commentUsers]" inside the array are also "promise" objects. Which means that they didn't contain the value data when they first been executed, until they got the value. So that "spread" function will wait the acture value come and continue doing the rest stuffs.

这篇关于Sails.js填充嵌套协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆