db.WorkbookQuestion.count({
where: {
QuestionId: dbQuestion.id,
AnswerSelectedId: db.sequelize.col('CorrectAnswerId')
}
});
The query generates this SQL: SELECT count(*) AS "count" FROM "WorkbookQuestions" AS "WorkbookQuestion" WHERE "WorkbookQuestion"."QuestionId" = 1103 AND "CorrectAnswerId";
How do I get it to be more like AnswerSelectedId = CorrectAnswerId
?
Sequelize instance comes with the query() method which you can use to run a raw query. The syntax of the method is as shown below: const [results, metadata] = await sequelize. query( "Your query here", { options } );
In sql we use not equal to sign ( != ) but in sequelize we use Op.ne in query like below example.
The Sequelize setters and getters might not be used here. So setting raw to true provides me the desired output with a cleaner look & feel.
findByPk The findByPk method obtains only a single entry from the table, using the provided primary key. const project = await Project. findByPk(123); if (project === null) {
I was stuck on this for a while today until I found this answer. I also found another way of doing the same query so will leave another answer here.
db.WorkbookQuestion.count({
where: {
CorrectAnswerId: {
$col: 'AnswerSelectedId'
}
}
});
Update: Another way of writing code by using Operators(Op) from sequelize.
const { Op } = require('sequelize');
db.WorkbookQuestion.count({
where: {
QuestionId: dbQuestion.id,
CorrectAnswerId: {
[Op.eq]: sequelize.col('AnswerSelectedId')
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With