如何根据长度来动态地将值添加到PostgreSQL查询中

问题描述 投票:2回答:1

我正在NodeJS API中构建一个辅助程序,可以根据客户端输入动态构建队列。现在,该查询以这种方式工作:

insertOne(table, columns, params) {
        return query(
            `INSERT INTO ${table}
                        (${columns})
                        VALUES ($1, $2, $3, $4, $5, $6)
                        RETURNING*`,
            params
        );
    }

该方法接受3个参数,即表名,列和要传递给查询的参数。我能够传递表名和列,但无法完成如何根据列的长度获得值$1 $2 ... $n。我的意思是,例如当客户编写3列要通过时,我应该动态生成$ 1 $ 2 $ 3。

我正在尝试for循环,但被卡住了:

let i = 0;
for (const propName in columns) {
    q = propName + " = $" + (i ++);
    params.push(q[propName]);
    i++;
}

我现在以这种方式调用此方法:

async createOne(req, res) {
        console.log({ ...req.body });
        try {
            const product = await Queries.insertOne(
                "products",
                [
                    "productname",
                    "description",
                    "brand",
                    "price",
                    "category",
                    "imageurl"
                ],
                [
                    req.body.productname,
                    req.body.description,
                    req.body.brand,
                    req.body.price,
                    req.body.category,
                    req.body.imageurl
                ]
            );
            res.json({ msg: "Product added", data: product.rows });
        } catch (err) {
            return res.json({ msg: "POST Something went wrong!", err: err });
        }
    },

助手在上述情况下应该看到传递了6列,并动态地将值从$ 1生成为$ 6。

想法是将其用于可以更改列数的不同表中。

我希望使自己更加清晰,如果您需要我的帮助,请发表评论。

javascript node.js postgresql
1个回答
0
投票

您要做的就是为$n数组中的每个元素返回一个以逗号分隔的params

您可以使用类似的方法做到这一点:

function createValuesIds(vals) {
  let ids = '';
  for (let i = 0; i < vals.length; i++) {
    ids += i === 0 ? '$1' : `, $${i + 1}`;
  }
  return ids;
}

使用createValuesIds(['a','b','c','d','e','f'])之类的名称返回$1, $2, $3, $4, $5, $6

然后您只需在函数中使用它:

insertOne(table, columns, params) {
  return query(
      `INSERT INTO ${table}
                  (${columns})
                  VALUES (${createValuesIds(params)})
                  RETURNING *`,
      params
  );
}

它将正确建立您的查询。

© www.soinside.com 2019 - 2024. All rights reserved.