【发布时间】: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