简体   繁体   English

如何使用 Bookshelf/Knex 在 Postgres 中插入/更新“ARRAY”列

[英]How to insert/update `ARRAY` column in Postgres using Bookshelf/Knex

I have a table in my Postgres database which contains a column with datatype ARRAY .我的 Postgres 数据库中有一个表,其中包含一个数据类型为ARRAY的列。 I am using Bookshelf to perform operations on the database.我正在使用 Bookshelf 对数据库执行操作。 Now, I want to insert/update (append new data to previous data in an array) data in this column and I could not find a way to do this.现在,我想在此列中插入/更新(将新数据附加到数组中的先前数据)数据,但我找不到执行此操作的方法。 Can anybody guide me on how I can achieve this?有人可以指导我如何实现这一目标吗? I think, one way of doing this could be using raw() function of Knex but I am not sure about how to use raw() function so please guide me on that too.我认为,这样做的一种方法可能是使用 Knex 的raw()函数,但我不确定如何使用raw()函数,所以也请指导我。 Thanks.谢谢。

I found the solution for this problem here .我在这里找到了这个问题的解决方案。 It seems BookshelfJS does not have a way to handle such operations so I had to use KnexJS. BookshelfJS 似乎没有办法处理此类操作,所以我不得不使用 KnexJS。 I implemented it something like this -我实现了这样的东西 -

knex('users')                               //users table
        .where('id', id)
        .update({
            array_column_name: knex.raw('array_append(array_column_name, ?)', [data_to_append])
        })
        .then(function (user) {
            //Do something 
        });

Hope this helps other people in future.希望这对将来的其他人有所帮助。

Assuming the following table schema假设下表架构

CREATE TABLE test (id SERIAL PRIMARY KEY, data TEXT[] NOT NULL);

with example data带有示例数据

INSERT INTO test (data) VALUES (array[ 'def', 'ghi' ]);

which can be queried like可以像这样查询

SELECT * FROM test ;
 id |   data    
----+-----------
  1 | {def,ghi}

You can use thearray functions to array_prepend( 'abc', array ) and array_append( array, 'xyz' ) like so您可以像这样使用array_prepend( 'abc', array )array_append( array, 'xyz' )数组函数

UPDATE test SET data = array_prepend( 'abc', data );
UPDATE test SET data = array_append( data, 'xyz' );

to get要得到

SELECT * FROM test;
id  |       data        
----+-------------------
  1 | {abc,def,ghi,xyz}

You should be aware that the data column is not atomic and therefore this table schema does not adhere to first normal form (violation of 1NF).您应该知道data列不是原子的,因此该表模式不符合第一范式(违反 1NF)。 It will be more difficult to filter out values from the data column.data列中过滤掉值会更加困难。 You cannot use the WHERE clause easily, for example.例如,您不能轻易地使用WHERE子句。 Consider adapting the table schema to adhere to 1NF, better 3NF at least.考虑调整表模式以遵守 1NF,至少更好的 3NF。

UPDATE tableName SET ColumnName = array_prepend( 'Value', ColumnName) WHERE ColumnName = 'Value' UPDATE tblTest SET TestColumnName = array_prepend( 'TestData', TestColumnName) WHERE TestColumnId = '1'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM