【问题标题】:How to convert PostgresQL command to SQL query builder syntax如何将 PostgreSQL 命令转换为 SQL 查询生成器语法
【发布时间】:2018-06-20 22:04:31
【问题描述】:

我有以下 Postgres 命令:

UPDATE users SET weightsovertime = weightsovertime || '{"weight":35,"date":"1/9/97"}'::jsonb where id = 20;

我想使用 Knex.js 等库将其转换为 SQL 查询生成器命令。

我试过这个:

postgres('users')
.where('id','=',id)
.update({
    weightsovertime: weightsovertime +'||' + data + '::jsonb' 
})
.returning('weightsovertime')
.then(response => {
    res.json(response[0]);
})
.catch(err => res.status(400).json('unable to get entries'));

但它不起作用,我也尝试将“weightsovertime”括在引号中,但出现错误“无法获取条目”。

非常感谢任何帮助。

【问题讨论】:

  • 如果您使用的是pg-promise,那么为什么会出现这种复杂情况?这只是一个带有pg-promise 的单行查询。
  • 我试过 pg promise,但也没用
  • 什么不起作用?如果您发布详细信息,那么您可以获得答案。
  • db.any('UPDATE users SET weightsovertime = weightsovertime || 'data'::jsonb where id = id);

标签: javascript postgresql knex.js pg-promise


【解决方案1】:

用 knex (https://runkit.com/embed/3ppka63pplpa):

knex('users').update({
  weightsovertime: knex.raw('?? || ?::jsonb', [
    'weightsovertime', 
    JSON.stringify({ weight: 35, date: '1/9/97' })
  ])
}).where('id', 20)

【讨论】:

    【解决方案2】:

    pg-promise 会是:

    const data = {
        id: 20,
        weightsovertime: {
            weight: 35,
            date: '1/9/97'
        }
    };
    
    db.none('UPDATE users SET weightsovertime = weightsovertime || ${weightsovertime}::jsonb WHERE id = ${id}', data)
        .then(() => {
            /* success */
        })
        .catch(error => {
             /* failure */
        });
    

    【讨论】:

      猜你喜欢
      • 2019-06-21
      • 1970-01-01
      • 2021-04-30
      • 2020-01-30
      • 2017-06-01
      • 2019-09-08
      • 2021-08-07
      • 2023-01-20
      • 2017-04-22
      相关资源
      最近更新 更多