Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting array into postgresql

I want to insert an array of id's to a file, but while creating a table I used int, and it has the reference of another table now how can I store array value to the specific field? I understand that the columns have to be the same type and I also saw that some tried to tackle this foreign key on array issue already: also i tried ELEMENT according to this doc but no success. please someone help me here https://blog.2ndquadrant.com/postgresql-9-3-development-array-element-foreign-keys/

db.query('CREATE TABLE IF NOT EXISTS departments_users(_id SERIAL NOT NULL UNIQUE PRIMARY KEY,user_id int REFERENCES companyUser ON DELETE CASCADE,department_id int REFERENCES departments ON DELETE CASCADE)');

exports.addCompanyUser = function(data, callback) {
    db.query('INSERT INTO departments_users(user_id,department_id) VALUES($1,$2) RETURNING *', [companyuseraccess.rows[0]._id, data.department]).then(function(departments_users) {      
    })
}
like image 254
Schüler Avatar asked Mar 16 '26 13:03

Schüler


1 Answers

You dont have any field with ARRAY dataType so essentially you cannot insert array into the field. If you wish to put in array in a field change its data type to ARRAY first and then you can

INSERT INTO "some_table" ("id","array_field","some_text_field") 
VALUES (1,ARRAY['value1','value2']::TEXT[],'active') RETURNING *

Hope this helps. Let me know if i can help further

like image 143
Hannan Avatar answered Mar 19 '26 03:03

Hannan