如何用 knex 重写原始 sql 查询?

How to rewrite raw sql query with knex?

我是开发新手,这是我第一次使用 knex。

问题: 我有一个原始的 SQL 查询,它工作正常。现在,我正在尝试使用 knex 进行此查询。为了了解一切是如何工作的,我想:

  1. 用knex.raw
  2. 重写查询
  3. 使用 knex 查询生成器重写查询。

有人可以帮我吗?顺便说一句,我正在使用 Postgres 和 Next.js。 通过 运行 下面的代码,我得到“UnhandledPromiseRejectionWarning: E​​rror: Expected 1 bindings, saw 0”。我不知道问题是否出在这里:

typeof req.query.word === 'string' ? [req.query.word] : req.query.word)

... 所以我已经尝试重写它(使用 [ ]),但它没有用。这是代码:

const getTranslation = (req, res) => {
  const params =
    typeof req.query.word === 'string'
      ? req.query.word
      : req.query.word.map((_, index) => `$${index + 1}`);
    console.log(req.query.word);

  knex.raw(
    `SELECT "Translation", "Words" FROM "Dictionary" WHERE "Words" IN (${
      typeof req.query.word === 'string' ? '()' : params.join(',')
    })`,
    typeof req.query.word === 'string' ? [req.query.word] : req.query.word)
    
      .then((error, result) => {
        const wordArray = typeof req.query.word === 'string' ? [req.query.word] : req.query.word;
        if (error) {
          throw error; 
        } 
        const wordOrder = req.query.word;
        result.rows.sort((row1, row2) => {
          return wordOrder.indexOf(row1.Words) - wordOrder.indexOf(row2.Words);
        });
        res.status(200).json(result.rows);
    }
  );
};

我试过的: 我尝试使用以下简单查询来检查配置是否正常工作。我认为确实如此:终端(网络)显示状态为 200 的请求,我在控制台中看到了数据...

const getTranslation = (req, res) => {
  knex.select("Words", "Translation").from("Dictionary")
      .then(rows =>
        rows.map(row => {
          console.log(row)
        }))
} 

谢谢!!

请记住,我实际上并不了解 Knex。

但是当我查看下面 link 中问题的一些答案时,我注意到他们使用了“Knex.with()”

knex.with('with_alias', knex.raw('select * from "lyrics" where "for_id" = ? and "var" = ?', [var1, var2])).select('*').from('with_alias')

所以他们似乎将其与“With_alias”绑定在一起。

他们还指定您应该尝试在数组中传递变量。

希望对你有所帮助。

您的查询应如下所示:

const results = await knex('Dictionary')
  .columns(['Translation', 'Words'])
  .whereIn('Words', req.query.word); // assumes that `req.query.word` is array with strings/numbers