【发布时间】:2019-05-29 01:43:23
【问题描述】:
我有两个模型,project 和 user,它们以多种方式相互关联。
首先,project 由具有以下关联的 user拥有:
Project.belongsTo(models.User, { as: 'Owner', foreignKey: 'userId' });
其次,project 和 user 通过 user 关联 喜欢 project。
Project.belongsToMany(models.User, { as: 'UserLikes', through: models.ProjectLikes, foreignKey: 'projectId' });
User.belongsToMany(models.Project, { as: 'LikedProjects', through: models.ProjectLikes, foreignKey: 'userId' });
第三,project 和user 也可以通过user 作为project 的一部分通过角色 关联。
Project.belongsToMany(models.User, { as: 'Users', through: models.ProjectRoles, foreignKey: 'projectId' });
User.belongsToMany(models.Project, { as: 'Roles', through: models.ProjectRoles, foreignKey: 'userId' });
我想要实现的是找到所有项目并连同它们一起返回相关的“喜欢”计数。但是我真的很难弄清楚如何做到这一点。
我已经读到我应该能够做类似的事情:
models.Project.findAll({
limit: 5,
attributes: ['Project.*', [models.sequelize.fn('COUNT', models.sequelize.col('UserLikes.id')), 'totalLikes']],
include: [ { model: models.User, as: 'UserLikes' }],
group: [ models.Project.rawAttributes.id, models.sequelize.col('UserLikes.id') ]
})
.then(function (projects) {
return res.json(projects);
});
但我收到 missing FROM-clause entry for table "UserLikes 错误。
我尝试使用特定的连接表模型将双方的关联更改为hasMany,然后执行以下操作:
models.Project.findAll({
limit: 5,
attributes: ['Project.*', 'ProjectLikes.id', [models.sequelize.fn('COUNT', models.sequelize.col('ProjectLikes.id')), 'totalLikes']],
include: [ { model: models.ProjectLikes }],
group: [ models.Project.rawAttributes.id ]
})
.then(function (projects) {
return res.json(projects);
});
但是我遇到了同样的错误,或者关于 Id 不明确的错误或关于 Project.id 需要在 GROUP BY 子句中的错误(即使它是?!)。
我正在竭尽全力想弄清楚一些应该非常直截了当的东西......我几乎正在考虑切换回 MongoDB!
请帮忙...谢谢!
【问题讨论】:
-
sql输出的是什么?
标签: node.js postgresql count associations sequelize.js