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
})
})
});
这是精细和功能,但不优雅。
只是想知道什么是一个查询解决方案。
非常感谢Gonzalo。它是有道理的和有效的。如果有人正在阅读并使用代码,我必须将订单行从我的原始代码更改为:order:[[“id”,“DESC”]] – tugboat