[SOLVED] using replacements with sequelize.literal()

Issue

I’m trying to use replacements with sequelize.literal() query.

router.get('/posts/testapik', function(req, res)
{

    const user_id = req.session.user_id;

    const status ="accept"
  Posts.findAll({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=? and `Follows`.status=?',{ replacements: [user_id,status], type: sequelize.QueryTypes.SELECT })]}}

                })
  .then(users => 
    {

        res.send(users);
  })

});

But it returns following error

original:
   { Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '? and `Follows`.status=?)' at line 1

Solution

This Works…
I have used this user_id = ‘+user_id+’

router.get('/posts/testapik', function(req, res)
{

    const user_id = req.session.user_id;

    const status ="accept"
  Posts.findAll({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='+user_id+' and `Follows`.status="accept")')]}}

                })
  .then(users => 
    {
        console.log("Posts data Testing =>",users);
        res.send(users);
  })
    .catch((err)=>
    {
        console.error(err)
        res.status(501)
        .send({
                error : "error..... check console log"
              })
    })


});

Answered By – cool

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.