【问题标题】:I want to merge two sequelize query into single sequelize query我想将两个 sequelize 查询合并为单个 sequelize 查询
【发布时间】:2019-02-22 07:23:29
【问题描述】:

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

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

});

【问题讨论】:

    标签: mysql sql node.js sequelize.js


    【解决方案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);
    })
    

    【讨论】:

      【解决方案2】:

      你可以试试这个。

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

      【讨论】:

      • 不,这将只返回那些像%${search}% 这样的the_cmets 的那些cmets,但是我们想要的是如果有像%${search}% 这样的the_cmets 中的任何一个,那么我们想要得到所有的cmets,这就是为什么上面绿色勾选的答案成立的原因,顺便感谢您的回复。
      猜你喜欢
      • 2015-10-14
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多