Amadou Beye Amadou Beye - 3 years ago 210
Node.js Question

Sequelize BelongsToMany: custom column in WHERE clause

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

Answer Source

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);
})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download