Sails.js 填充嵌套关联 [英] Sails.js populate nested associations

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

问题描述

我有一个关于 Sails.js 0.10-rc5 版中关联的问题.我一直在构建一个应用程序,其中多个模型相互关联,但我已经到了需要以某种方式嵌套关联的地步.

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.

分为三部分:

首先是用户撰写的博客文章之类的内容.在博客文章中,我想显示关联用户的信息,例如他们的用户名.现在,这里一切正常.直到下一步:我正在尝试显示与帖子相关的评论.

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>

comment.user.name 将是未定义的.如果我尝试只访问用户"属性,例如 comment.user,它会显示它的 ID.这告诉我,当我将评论与另一个模型相关联时,它不会自动将用户信息填充到评论中.

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 :)?

提前致谢!

附言

为了澄清,这是我在不同模型中基本设置关联的方式:

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'
}

推荐答案

或者你可以使用内置的 Blue Bird 承诺功能来实现它.(在 Sails@v0.10.5 上工作)

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

查看以下代码:

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);
  });

一些解释:

  1. 我正在使用 Lo-Dash 来处理数组.更多详情请参考官方文档
  2. 注意第一个then"函数中的返回值,数组中的那些对象[post, commentUsers]"也是promise"对象.这意味着它们在第一次执行时不包含值数据,直到它们获得值.因此,传播"函数将等待实际值到来并继续做其余的事情.
  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天全站免登陆