节点 pg-promise,使用类型转换绑定多个值



我目前正在使用 pg-promise 库将多个值插入到数据库中,格式如下:

const cs = new pgp.helpers.ColumnSet(['booking_id', {name:'timeslot', cast:'timestamp'}], {table: 'booking'});
// data input values:
const values = [];
bookings.forEach(slot => {
values.push({booking_id: booking_id, timeslot: slot});
});

我需要时隙作为时间戳的地方。但是,它作为值进入 API 中,例如

1515586500.0

使用上面的cast属性,我的查询可以这样解析

insert into "booking"("booking_id","timeslot") values(1,'1515586500.0'::timestamp)

但是,这会引发错误cannot cast type numeric to timestamp without time zone

但是,如果我使用to_timestamp函数,这将按照我需要的方式工作,例如

insert into "booking"("booking_id","timeslot") values(1,to_timestamp('1515586500.0'));

有什么方法可以让 pg-promise 使用to_timestamp而不是::timestamp符号吗?

将列定义更改为以下列:

{
name: 'timeslot',
mod: ':raw',
init: c => pgp.as.format('to_timestamp($1)', c.value)
}

{
name: 'timeslot',
mod: ':raw',
init: c => pgp.as.format('to_timestamp(${value})', c)
}

。根据列类型文档。

或者,您可以对文字使用"自定义文字格式",以自动自行格式化。


此外,您不需要重新映射值以适应ColumnSet对象,而是使用ColumnSet对象来拟合数据。因此,如果列timeslot的值位于属性slot中,您只需在列定义中使用prop: 'slot'来更改值的来源。

最新更新