I am working with the following data on sequelize:
{
name: "Matti Luukkainen",
username: "[email protected]",
wish_read: [
{
id: 3,
url: "https://google.com",
title: "Clean React",
author: "Dan Abramov",
likes: 34,
year: null,
reading_lists: [
{
read: true,
id: 2
}
]
},
{
id: 4,
url: "https://google.com",
title: "Clean Code",
author: "Bob Martin",
likes: 5,
year: null,
reading_lists: [
{
read: false,
id: 2
}
]
}
]
}
I want to filter the data using the command where, to show just the blogs where reading_lists.read = true. My implementation is the following code, but the filter does not work. I imagine that I can't pass an object directly in where, but I could not think in another way to do it.
const user = await User.findByPk(req.params.id,{
attributes: { exclude: ['id', 'createdAt', 'updatedAt']},
include: [
{
model: Blog,
as: 'wish_read',
attributes: { exclude: ['userId']},
through: {
attributes: { exclude: ['user_id', 'blog_id', 'blogId', 'userId'] }
},
attributes: { exclude: ['id', 'createdAt', 'userId', 'updatedAt'] }
},
],
where: {
wish_read.reading_lists.read: true
}
})
CodePudding user response:
You need to wrap a column path with $ like this:
where: {
'$wish_read.reading_lists.read$': true
}
CodePudding user response:
You're using findByPk (find by private key). You use that function when you already have the ID and just want to load an object. You should use findOne for work with filters. In addition, if reading_list is also an entity, you can nest the include parameters and use where parameters inside.
E.g:
include: [ { model: Blog, as: 'wish_read', include: [ { model: ReadingList, as: 'reading_lists', where: {read: true} } ] } ]
