Reputation: 2808
I have this 3 models:
var User = sequelize.define('users', {
name: {
type: DataTypes.STRING(50),
field: 'name'
}
});
var Book = sequelize.define('books', {
name: {
type: DataTypes.STRING(50),
field: 'name'
}
});
var UserBook = sequelize.define('userbook', {
validated: {
type: DataTypes.INTEGER,
field: 'validated',
defaultValue: 0
}
});
Book.belongsToMany(User, {through: UserBook, foreignKey: 'bookId'});
User.belongsToMany(Book, {through: UserBook, foreignKey: 'userId'});
Now I want to get books for a user where validated=1
I have tried this:
User.findOne({
where: { id: req.session.user.id }
})
.then(function(user){
user.getBooks({
through: { validated: 1 }
})
.then(function(books){
return res.json({success: true, books: books});
})
});
But it returns all books without checking for validated=1
How to get all books with validated=1 ?
Thank you
Upvotes: 0
Views: 1405
Reputation: 2026
I've you tried this :
User.findOne({
where: { id: req.session.user.id }
})
.then(function (user) {
user.getBooks({
where: { validated: 1 }
})
.then(function (books) {
return res.json({ success: true, books: books });
})
});
?
Edit (it works):
User.findById(req.session.user.id, {
include: [
{
model: Book,
through: {
where: { validated: 1 }
}
}
]
}).then((user) => {
console.log(user);
})
Upvotes: 2