首页 > 解决方案 > Sails.js 计算模型/关联的成员

问题描述

我正在尝试在这样的屏幕截图中计算团队成员:

截图sails.js 计数函数

这是我的“逻辑”,但它不起作用:(

  fn: async function () {

    var teams = await Team.find();
    var users = await User.find();

    var countMembers = await Team.count().where(users.team === teams.id);

    // Respond with view.
    return {teams, countMembers};

  }

表/模型用户是这样的,即 1 个用户可以拥有 1 个团队。我只想计算团队概述页面中的成员。

标签: javascriptnode.jscountsails.jswaterline

解决方案


如果您设置了您的模块,即使用users: {collection: 'User', via: 'team'}集合的属性Teams,以及User使用 属性的模块,请尝试此操作team: {model: 'Team'}

一对多文档:https ://sailsjs.com/documentation/concepts/models-and-orm/associations/one-to-many#one-to-many

fn: async function () {

    // Populate and count for many-to-one relationship (one team has many members)
    var teams = await Team.find().populate('users');
    teams = teams.map(team => ({
      ...team,
      countMembers: team.users.length,
    }));

    // Respond with a view.
    return { teams };

}

在您的 EJS 视图中使用:

<% teams.forEach(team => { %>
 <%= team.countMembers %>
<% }) %>

在此处检查选项以考虑填充项目的限制以避免计数值错误:https ://sailsjs.com/documentation/reference/waterline-orm/queries/populate

或者,您可以使用本机查询:

https://sailsjs.com/documentation/reference/waterline-orm/datastores/send-native-query#-sendnativequery-

甚至低级适配器使用:

https://sailsjs.com/documentation/tutorials/using-mongo-db


推荐阅读