Sails.js 计算模型/协会的成员

Sails.js Count members of model / assiciation

我正在尝试计算 table 中的团队成员,如下图所示:

这是我的“逻辑”,但行不通:(

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

  }

Table/模型用户是这样的,1个用户可以有1个团队。 我只想在团队概览页面中统计成员。

如果您设置模块,请尝试此操作,即使用属性 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