我有这3个型号:
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'});
现在我想为有效的用户获取书籍= 1
我试过这个:
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});
})
});
但它返回所有书籍而不检查validated = 1
如何获取所有经过验证的图书= 1?
谢谢
答案 0 :(得分:1)
我试过这个:
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 });
})
});
编辑(可行):
User.findById(req.session.user.id, {
include: [
{
model: Book,
through: {
where: { validated: 1 }
}
}
]
}).then((user) => {
console.log(user);
})