如何用用户输入替换 Sequelize 原始查询中的参数?

How to replace parameter in Sequelize raw query with user input?

我有一个搜索栏,我想使用用户输入通过 Sequelize 原始查询进行查询。我在这里缺少什么以及为什么它不起作用?

router.get('/search', (req, res) => {
    let { term } = req.query;

    db.query(
        'SELECT * FROM locations WHERE code= :term',
        { replacements: term, raw: true, type: QueryTypes.SELECT})
        .then(locations => res.render('locations', { locations }))
        .catch(err => console.log(err));
    
})

您需要将对象传递给替换项:replacements: { term },您只是传递字符串 term,解决方案:

router.get('/search', (req, res) => {
let { term } = req.query;

db.query(
    'SELECT * FROM locations WHERE code= :term',
    { replacements: { term } , raw: true, type: QueryTypes.SELECT})
    .then(locations => res.render('locations', { locations }))
    .catch(err => console.log(err));

})

参考文档中的示例:https://sequelize.org/master/manual/raw-queries.html

await sequelize.query(
  'SELECT * FROM users WHERE name LIKE :search_name',
  {
    replacements: { search_name: 'ben%' },
    type: QueryTypes.SELECT
  }
);