本文介绍了如何使用 Sequelize + PostgreSQL 将项目附加到数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 posgresql 数据库,表有一列是一个数组:Sequelize.ARRAY(Sequelize.BIGINT).

I have a posgresql database, table has a column which is an array: Sequelize.ARRAY(Sequelize.BIGINT).

将新项目附加到数组的正确方法是什么?

What is the right way to append a new item to the array?

我是 posgresql、sequelize 和 nodejs 的新手.可能这是一个微不足道的问题.通过阅读,我想我知道如何使用 Promise.all 来读取所有行、追加和更新回来.问题是,有没有什么有用的捷径.

I am new to posgresql, sequelize and nodejs. May be it is a trivial question.From reading around I think I know how to use Promise.all to read all rows, append, and update back.The question, isn't there any useful shortcut.

PostreSQL 文档 提到了一个函数 array_append(anyarray, anyelement).

Sequelize 文档提供函数 fn,它创建一个表示数据库函数的对象,但似乎只在 where 和 order 部分

Sequelize documentation offers a function fn, which Creates an object representing a database function, but only seems to be working in where and order parts

有什么方法可以将它们结合起来进行类似追加的更新?

Any way to combine those for an append-like update?

推荐答案

Array Datatype 有很多方法,比如 append、concat 等等,你可以看看 这里.我将举例说明 array_append 函数.

Array Datatype has many methods like append, concat etc. which you can see here. I will give an example with array_append function.

Room 是一个续集模型,job_ids 是该模型中的一列,数据类型为整型数组.sequelize 是 Sequelize 类的一个瞬间.

Room is a sequelize model and job_ids is a column in this model with datatype as Array of integer. sequelize is an instant of Sequelize class.

Room.update(
 {'job_ids': sequelize.fn('array_append', sequelize.col('job_ids'), new_jobId)},
 {'where': {'id': roomId}}
);

假设此列的默认值是一个空数组,否则可能会引发错误.

Assuming default value of this column is an empty array else it may throw an error.

这篇关于如何使用 Sequelize + PostgreSQL 将项目附加到数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 08:52