2016-02-10 105 views
1

我試圖使用sequelizejs從博客表中獲取最新的博客文章,包括所有相應的註釋(來自單獨的註釋表)已被批准。評論數據庫有一個字段「blog_id」,它具有相應的博客ID。sequelize.js在連接表上使用where子句連接兩個表

如果我這樣做:

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

這是精細和功能,但不優雅。

只是想知道什麼是一個查詢解決方案。

回答

2

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

非常感謝Gonzalo。它是有道理的和有效的。如果有人正在閱讀並使用代碼,我必須將訂單行從我的原始代碼更改爲:order:[[「id」,「DESC」]] – tugboat