代码之家  ›  专栏  ›  技术社区  ›  Lin Du Correcter

如何使用knex.raw()方法将对象插入PostgreSQL数据库?

  •  0
  • Lin Du Correcter  · 技术社区  · 7 年前

    我正在寻找一种方法将对象插入 postgreSQL db使用knex.raw()方法。

    这是我的尝试,它有效,但我不知道这是否是最好的方法。

      const newLink = {
        url: 'http://github.com',
        name: 'GitHub',
        description: 'GitHub is awesome',
        rel: '',
        last_update: new Date()
      };
      const columns = Object.keys(newLink);
      const values = Object.values(newLink);
      console.log('columns: ', columns);
      console.log('values: ', values);
      const sql = `
        INSERT INTO link (${columns.map(col => col).join(',')})
        VALUES (${values.map(() => '?').join(',')})
      `;
      console.log('sql: ', sql);
      try {
        const insertObjResp = await knex.raw(sql, values);
        console.log('insertObjResp: ', insertObjResp);
      } catch (error) {
        console.error(error);
      }
    

    knex 给我这样的调试信息:

    { method: 'raw',
      sql: '\n    INSERT INTO link (url,name,description,rel,last_update)\n    VALUES (?,?,?,?,?)\n  ',
      bindings:
       [ 'http://github.com',
         'GitHub',
         'GitHub is awesome',
         '',
         2018-11-20T04:47:21.085Z ],
      options: {},
      __knexQueryUid: '304fb5e5-9864-4ec6-9a63-1051e8e3c9ad' }
    

    有没有 knex.js 这项工作的官方方式?谢谢。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Mikael Lepistö    7 年前

    有没有Knex.js的官方方式来完成这项工作?谢谢。

    官方方式是使用 knex.insert() .

    您的代码似乎是正确的,没有更好的方法。值数组和 knex.raw 使用起来有点不方便。当然,你至少应该把那个怪物包装在一个助手函数中。