sequelize.js查询连接两个表与连接表上的where子句

我正在尝试使用sequelizejs从博客表中获取最新的博客文章,其中包括所有已批准的相应注释(来自单独的注释表)。 评论数据库有一个字段“blog_id”,它具有相应的博客ID。

如果我这样做:

models.blogs.hasMany(models.comments, {foreignKey:'blog_id'}) models.comments.belongsTo(models.blogs, {foreignKey:'blog_id'}) models.blogs.findAll({where:{id:id},order:"id DESC", limit:1, include: [{model: models.comments, where:{approved:true}}]}).then(function(blogs){ res.json(blog:blogs[0]) }); 

结果是最近的博客文章一个已被批准的评论,而不是最近的博客文章任何已被批准的评论。

我的工作是有两个查询:

 models.blogs.findAll({order:[["id","DESC"]],limit:1}).then(function(blogs){ var blog = blogs[0]; models.comments.findAll({where:{"blog_id":blog.id,"approved": true}}).then(function(comments){ res.json({ blog:blog, comments:comments }) }) }); 

这是很好,function,但不优雅。

只是想知道什么是一个查询解决scheme。

你需要在你的include中指定required false,默认是true。

 models.blogs.findAll({ where: { id: id }, order: "id DESC", limit: 1, include: [{ required : false, model: models.comments, where: { approved: true } }] }) .then(function(blogs) { res.json(blog: blogs[0]) });