使用sequelize.literal() 进行替换

coo*_*ool 6 mysql sql node.js express sequelize.js

我正在尝试将替换与sequ​​elize.literal() 查询一起使用。

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

});
Run Code Online (Sandbox Code Playgroud)

但它返回以下错误

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
Run Code Online (Sandbox Code Playgroud)

小智 10

对于替换,您必须在查询对象内设置 replacements 属性。

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 }],
    replacements: [user_id, status],
    where: {
      user_id: {
        [Op.in]: [
          sequelize.literal(
            "SELECT `Follows`.receiver_id FROM `follows` AS `Follows` WHERE `Follows`.user_id=? and `Follows`.status=?"
          ),
        ],
      },
    },
  }).then((users) => {
    res.send(users);
  });
});

Run Code Online (Sandbox Code Playgroud)


coo*_*ool -28

这有效...我已经使用了这个 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"
              })
    })


});
Run Code Online (Sandbox Code Playgroud)

  • 这可能很危险,因为 user_id 不受保护并可能导致 SQL 注入。 (8认同)