sequelize.js查询在连接表上使用where子句连接两个表

时间:2016-02-10 02:23:06

标签: node.js express sequelize.js

我正在尝试使用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
        })
    })
});

这很好但很实用但不优雅。

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

1 个答案:

答案 0 :(得分:2)

您需要在include中指定必需的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])
});
相关问题