【发布时间】:2020-06-03 23:15:05
【问题描述】:
我正在处理一个返回用户名、ID 以及属于该用户的操作和 cmets 的数量的查询。这是 SQL 中的查询:
SELECT users.id, users.name, (
SELECT count(*) from actions where users.id = actions.user_id
) as Action_Count, (
SELECT count(*) from comments where users.id = comments.user_id
) as Comment_Count
FROM users
我对 Sequelize 有点陌生,但是经过太多小时的搜索和无数次尝试,我似乎无法弄清楚如何正确编写它。所以我希望这里有人可以帮助指导我。这是我最好的尝试:
User.findAll({
attributes: ['name','id',
[Sequelize.fn('count', Sequelize.col('actions.user_id')), 'count_of_actions'],
[Sequelize.fn('count', Sequelize.col('comments.user_id')), 'count_of_comments']
],
include: [{ attributes: [], model: Action },{ attributes: [], model: Comment }],
group: ['user.id'],
order: [['createdAt', 'ASC']]
})
但是如果有任何 cmets,这对于 Action_Count 和 Comment_Count(两者相乘)返回相同的数字。
非常感谢任何帮助或指导!
【问题讨论】:
-
我使用
sequelize.query运行上面的sql查询,它有效。如果可能的话,我仍然很好奇如何使用 sequelize 语法来做到这一点。
标签: sequelize.js