Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a SQL query for Sequelize?

I have a SQL query (using mysql as DB) that I now need to rewrite as a sequelize.js query in node.js.

SQL Query

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

not quite sure how this query needs to be structured to get the same results with sequelize.

like image 818
Patrick Fain Avatar asked Dec 19 '17 00:12

Patrick Fain


1 Answers

This should do what you're needing:

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) => {
  ...
})
like image 140
aecend Avatar answered Sep 24 '22 05:09

aecend