具有pg-promise的复合类型

时间:2017-05-01 07:50:52

标签: postgresql pg-promise

以下是一个示例代码:

battle.heroes = [{ id: hero.id, name: hero.name }]; //This is my array I want to insert
await db.one('INSERT INTO battles(mode, params, heroes) VALUES(${mode}, ${params}, ${heroes}) RETURNING id', {
    mode: battle.mode,
    params: battle.params,
    heroes: battle.heroes,
});

PostgreSQL类型'hero_info':

id int4
name varchar

1 个答案:

答案 0 :(得分:0)

通过Custom Type Formatting展示每个数组元素,方法是使用rawTypetoPostgres扩展现有对象,或使用您自己的自定义类型,如下所示:

const hero = (id, name) => ({
   rawType: true,
   toPostgres: () => pgp.as.format('($1, $2)::hero_info', [id, name])
});

用法示例:

const heroes = [hero(1, 'first'), hero(2, 'second')];

await db.one('INSERT INTO battles(mode, params, heroes) VALUES(${mode}, ${params}, ${heroes}) RETURNING id', {
    mode: battle.mode,
    params: battle.params,
    heroes
});

对于上面的代码,您的heros数组的格式正确为:

array[(1, 'first')::hero_info, (2, 'second')::hero_info]