Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using findByPk and WHERE condition in sequelize

Tags:

sequelize.js

In Sequelize I´m using findByPk but I also need to pass another condition

const options = {
    where: { role: 'admin' },
};

return models.User.findByPk(id, options)
    .then((user) => {...

But this query is retuning all users even if the role is not admin. I checked the SQL generated and I see SELECT * from User WHERE id = 1 but I don´t see the AND role = 'admin'. how to use findByPk and pass another condition?

thank you

like image 367
handsome Avatar asked Nov 29 '19 21:11

handsome


People also ask

Is findByPk faster than findOne?

Under the hood, there is no difference between passing a pk to findOne or using findByPk , i.e the performance is the same.

What is findByPk?

findByPk() Finds a single active record with the specified primary key. CActiveRecord.


1 Answers

You'll have to use findOne instead, and pass the primary key as a field in the where object:

return models.User.findOne({
  where: {
    id: id,
    role: 'admin', 
  },
})

The Sequelize documentation can be a little cluttered... But, the options argument in findByPk doesn't take the same values as the one in findOne. If you look closely at the documentation for findByPk, you'll see a note at the bottom that reads:

See: Model.findAll for a full explanation of options, Note that options.where is not supported.

like image 197
jknotek Avatar answered Sep 22 '22 04:09

jknotek