将SQL查询转换为Sequelize查询格式

时间:2019-07-06 19:15:23

标签: mysql express sequelize.js

我是Sequelize ORM的新手。我想将SQL查询转换为Sequelize查询。

这是我的SQL查询,我想将此查询转换为序列查询:

SELECT * FROM `Posts` AS `Posts` 
    WHERE `Posts`.user_id IN 
        (SELECT `Follows`.receiver_id FROM `follows` AS `Follows` 
            WHERE `Follows`.user_id = user_id and `Follows`.status = "accept");

我已经尝试过了,但是它不返回任何数据:

Posts
    .findAll({ where: { 
        user_id: { [Op.in]: [{
                include: [{
                    model: Follows,
                    attributes: ['receiver_id'],
                    where: { 
                        user_id: user_id,
                        status:status
                    }
                }]
            }]
        }
    }})
    .then(users => { res.send(users); })

执行上述代码后,它会在控制台中显示错误

SELECT `event_id`, `user_id`, `event_message`, `e_imagepath`, 
    `createdAt`, `updatedAt`, `receiver_id` 
    FROM `Posts` AS `Posts` 
    WHERE `Posts`.`user_id` IN ('[object Object]');

我想将SQL查询转换为Sequelize查询。

2 个答案:

答案 0 :(得分:0)

您将自己的指示放在错误的位置。据我所知,Sequelize没有子查询功能。

所以您可以改为:

Posts
    .findAll({ where: { user_id: user_id},
               include: [{
                    model: Follows,
                    attributes: ['receiver_id'],
                    where: { 
                        user_id: user_id,
                        status:status
                    }
                }]

    })
    .then(users => { res.send(users); })

如果上面的示例不适合您的需求。您还可以尝试通过将原始SQL与Sequelize混合使用子查询,如下面的链接所述:

stackoverflow.com/questions/28286811/sequelize-subquery-as-field

答案 1 :(得分:0)

This works fine.

router.get('/posts', function(req, res)
{
    const user_id = req.session.user_id;
    const status = "accept";
    Posts.findAndCountAll({include:[{ model: Likes},{ model: Comments},{ model: Users}],
        where:{user_id:{[Op.in]:[sequelize.literal('SELECT `Follows`.receiver_id FROM `follows` AS `Follows` WHERE `Follows`.user_id=1 and `Follows`.status="accept')]}}

        })
    .then((postdata)=>
    {

        Users.findAll({where:{user_id:user_id}})
        .then((userdata)=>
        {
            res.send(postdata.rows)
           // res.render('home',{title:'home',items:postdata.rows,user:userdata});
        }) 
        .catch((err)=>
        {

        })

    })
    .catch((err)=>
    {

    })


});