为了账号安全,请及时绑定邮箱和手机立即绑定

Sails.js填充嵌套关联

Sails.js填充嵌套关联

眼眸繁星 2019-08-27 16:15:28
Sails.js填充嵌套关联我自己有一个关于Sails.js版本0.10-rc5中的关联的问题。我一直在构建一个应用程序,其中多个模型相互关联,我到达了一个我需要以某种方式获得嵌套关联的点。有三个部分:首先是博客文章,这是由用户编写的。在博客文章中,我想显示关联用户的信息,如用户名。现在,这里一切正常。直到下一步:我正在尝试显示与帖子相关的评论。注释是一个单独的模型,称为Comment。每个人还有一个与之相关的作者(用户)。我可以轻松地显示评论列表,但是当我想显示与评论相关的用户信息时,我无法弄清楚如何使用用户的信息填充评论。在我的控制器中,我试图做这样的事情: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.   });在我的Post''show'动作中,我试图检索这样的信息(简化):<ul>    <%- _.each(post.comments, function(comment) { %>     <li>       <%= comment.user.name %>       <%= comment.description %>     </li>   <% }); %></ul>但是,comment.user.name将是未定义的。如果我尝试只访问'user'属性,例如comment.user,它会显示它的ID。这告诉我,当我将评论与其他模型关联时,它不会自动将用户的信息填充到评论中。任何理想的人都能妥善解决这个问题:)?提前致谢!PS为了澄清,这就是我基本上在不同模型中建立关联的方式:// User.jsposts: {   collection: 'post'},   hours: {   collection: 'hour'},comments: {   collection: 'comment'}// Post.jsuser: {   model: 'user'},comments: {   collection: 'comment',   via: 'post'}// Comment.jsuser: {   model: 'user'},post: {   model: 'post'}
查看完整描述

3 回答

?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

或者您可以使用内置的Blue Bird Promise功能来制作它。(致力于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”对象。这意味着它们在首次执行时不包含值数据,直到它们获得值。因此,“传播”功能将等待动作值来继续做剩下的事情。


查看完整回答
反对 回复 2019-08-27
  • 3 回答
  • 0 关注
  • 650 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信