[英]How to insert ARRAY data type using knex and potsgres
I'm encountring this issue and i'm running out of time so please if anyone could help: I want to insert this data: 我正在解决此问题,时间用完了,所以请有人帮忙:我想插入以下数据:
const data= {
id:user.id,
choice:'SWOT',
label:['Strengths','Weaknesses','Opportunities','Threats'],
results:[45,5,20,30],
description:'My first Strategic Analysis'}
into this table: 进入此表:
analyses (
id serial primary key,
userID integer not null,
choice varchar(25) not null,
Label text ARRAY,
Results integer ARRAY,
description varchar(200),
FOREIGN KEY (userID) REFERENCES users (id)
); );
Using knex, this should be smth like: 使用knex,应如下所示:
db('analyses').insert({
userid: data.id,
choice: data.choice,
Label: data.labelG,
Results: data.resultG,
description: data.description
})
Since this syntax doesn't work for ARRAY types I wonder how to do it ? 由于此语法不适用于ARRAY类型,所以我想知道如何做? Some suggested to use knex.raw() however I coudn't get the right syntax for that Any help?
有些人建议使用knex.raw(),但是我无法获得正确的语法。有帮助吗?
You can directly pass javascript arrays to your ARRAY
type of columns. 您可以直接将javascript数组传递给
ARRAY
类型的列。 Like this: 像这样:
await knex.schema.createTable('foo', t => {
t.increments('id');
t.specificType('intarray', 'integer ARRAY');
t.specificType('stringarray', 'text ARRAY');
});
await knex('foo').insert({ intarray: [4,3,2,1], stringarray: ['foo','bar'] });
const rows = await knex('foo');
console.log(rows);
// should output:
// [ anonymous { id: 1, intarray: [ 4,3,2,1 ], stringarray: [ 'foo', 'bar' ] } ]
For Postgresql's text array you need to store your data like: 对于Postgresql的文本数组,您需要像这样存储数据:
{'Strengths','Weaknesses','Opportunities','Threats'}
For doing that you can create a function to convert it to common use. 为此,您可以创建一个将其转换为常用功能的函数。
db('analyses').insert({
userid: data.id,
choice: data.choice,
Label: '{"' + data.labelG.join('","') + '"}',
Results: data.resultG,
description: data.description
})
Also you need to convert it when you fetched them too. 另外,您也需要在获取它们时进行转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.