我想将两个sequelize查询合并为一个sequelize查询

时间:2019-02-22 07:23:29

标签: mysql sql node.js sequelize.js

我要查找的内容是,首先选择包含我的搜索参数的评论,它将返回postId,然后选择包含所有评论的整个帖子,包括我们使用搜索参数搜索过的评论!

app.get('/search_', (req, res, next) => {
    var search = req.query.search;

comment.findAll({
        attributes: ['PostId'],
        where: {
            the_comments: {
                [Op.like]: `%${search}%`
            }
        }
    })
    .then(data => {
        var array = [ ];
        for (var x in data) {
            console.log(data[x].PostId);
            array.push(data[x].PostId);
        }
        console.log(array);
        Post.findAll({
                include: [
                    {
                        model: comment
                    }
                ],
                where: {
                    id: {
                        [Op. in]: [array]
                    }
                }
            })
            .then(result => {
                res.json(result);
         })
    })

});

2 个答案:

答案 0 :(得分:1)

  Post.findAll({
    include: [{
        model: comment
    }],
    where : {
        id : {
            [Op.in] : [connection.literal(`select PostId from comment where the_comments like '%${search}%'`)]
        }
    }
})
.then(result => {
    console.log('result',result);
    res.json(result);
}).catch(error=>{
    console.log(error);
    res.json(error);
})

答案 1 :(得分:1)

您可以尝试一下。

Post.findAll({
    include: [
        {
            model: comment,
            required: true,
            where: {
                    the_comments: {
                                    [Op.like]: `%${search}%`
                                  }
                   }
        }
    ]
})