【问题标题】:sequelize.js query joining two tables with a where clause on the joined tablesequelize.js 查询使用连接表上的 where 子句连接两个表
【发布时间】:2016-03-04 11:00:52
【问题描述】:

我正在尝试使用 sequelizejs 从博客表中获取最新的博客文章,包括所有已批准的相应 cmets(来自单独的评论表)。 cmets 数据库有一个字段“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])
});

结果是最近条评论已获批准的博文,而不是最近的博文已获批准的任何 cmets。

我的解决方法是有两个查询:

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
        })
    })
});

很好用,但不优雅。

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

【问题讨论】:

    标签: node.js express sequelize.js


    【解决方案1】:

    您需要在 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])
    });
    

    【讨论】:

    • 非常感谢,贡萨洛。这是有道理且有效的。如果有人正在阅读此代码并使用该代码,我必须将订单行从我的原始代码更改为: order:[["id","DESC"]]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多