Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I query for two columns to be equal using Sequelize?

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?

like image 460
Shamoon Avatar asked Feb 27 '16 03:02

Shamoon


People also ask

How do you query in Sequelize?

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 } );

Is not equal in Sequelize?

In sql we use not equal to sign ( != ) but in sequelize we use Op.ne in query like below example.

Why we use raw true in Sequelize?

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.

What is findByPk?

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) {


2 Answers

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'
    }
  }
});
like image 104
nasoj1100 Avatar answered Oct 19 '22 02:10

nasoj1100


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')
    }
  }
});
like image 42
Solomon Raja Avatar answered Oct 19 '22 04:10

Solomon Raja