最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何为Sequelize转换SQL查询?

运维笔记admin11浏览0评论

如何为Sequelize转换SQL查询?

如何为Sequelize转换SQL查询?

我有一个SQL查询(使用mysql作为DB),我现在需要在node.js中重写为sequelize.js查询。

SQL查询

SELECT p.UserID, SUM(p.score), u.username
FROM Picks p
LEFT JOIN Users u
ON p.UserId = u.id
GROUP BY p.UserId;

不太确定如何构造此查询以获得与sequ​​elize相同的结果。

回答如下:

这应该做你需要的:

db.Pick.findAll({
  attributes: [
    'UserID',
    [db.sequelize.fn('SUM', db.sequelize.col('score')), 'score']
  ],
  include: [{
    model: db.User,
    required: true,
    attributes: ['username']
  }],
  group: ['UserID']
}).then((results) => {
  ...
})

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论