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
Under the hood, there is no difference between passing a pk to findOne or using findByPk , i.e the performance is the same.
findByPk() Finds a single active record with the specified primary key. CActiveRecord.
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.
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