在将数组插入到PostgreSQL列时出现了错误的数组字面量
P粉141925181
P粉141925181 2024-01-29 15:46:16
0
1
482

我在我的应用程序中使用 objection.js。

在尝试将字符串数组插入到PostgreSQL数据库列时,遇到了一个问题。该列的定义如下:

path TEXT[] NOT NULL

这是模式:

path: { type: 'array', items: { type: 'string' }, notNull: true }

我想使用upsertGraphAndFetch(objection.js)更新表列,但在更新和插入时,插入列path时出现错误

return NotificationUserOption.query().upsertGraphAndFetch(
        { userId: ctx. user, path, groupId, option },
        { insertMissing: true },

当我传递类似于['chat']的path时

await updateGlobalChatNotificationOptIn({
      variables: {
        path: ['chat'],
        option: updatedGlobalChatNotificationOptIn ? '30MinSummary' : 'off',
      },
    })
  }

然而,当我尝试使用这段代码插入数组时,遇到了以下错误:

数组文字格式错误:“[”chat“]” “[”必须明确指定数组维度。

我尝试使用单括号('{chat}')和双括号([['chat']]),但都无效。

如何正确格式化数组文字,以便在插入到PostgreSQL列时不遇到此错误?

P粉141925181
P粉141925181

全部回复(1)
P粉009828788

要将字符串数组插入到PostgreSQL的TEXT[]类型的列中,您需要将JavaScript数组转换为字符串表示形式,使用花括号和双引号包裹每个元素。

Objection.js中执行以下操作:

// 将数组转换为字符串表示形式
const pathArray = ['chat'];
const pathString = `{${pathArray.join(',')}}`;

// 使用Objection.js将数据插入数据库
await NotificationUserOption.query().upsertGraphAndFetch(
  { userId: ctx.user, path: pathString, groupId, option },
  { insertMissing: true }
);

现在TEXT[]将不会出现任何"malformed array literal"错误。在从数据库查询数据时,Objection.js将处理将其转换回JavaScript数组。

#Apache-Age #posgresql #graphql #objection.js

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!