javascript - 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 个团队。我只想计算团队概述页面中的成员。
解决方案
如果您设置了您的模块,即使用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
或者,您可以使用本机查询:
甚至低级适配器使用:
推荐阅读
- amazon-web-services - 从 AWS CDK 堆栈中获取所有节点
- python - 如何从 DeepDiff 中删除特定单词?
- java - 有没有更好的方法来处理双打的数学计算?
- java - 反应流中不一致的 doAfterTerminate 行为
- c# - 无法批量加载。文件“C:\CSV\Alarm.csv”不存在或您没有文件访问权限。-- SQL Server
- java - 禁用自定义健康检查端点
- python - Google Colab 不会运行所有一个单元格
- python - CVXPY 二次规划;ArpackNoConvergence 错误
- reactjs - 如何根据 React APP 中网站上的语言使元标记动态化?[反应头盔 + i18next]
- qt - 在 Linux 下从源代码编译 Qt5Quick 和 Qt5Qml