3

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) {      
    })
}
1

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

6 Comments

but @hannan we already created 5 tables which has references from one another i need to store multiple id's only to departments so do you have any idea on Foreign key constraint for array-field?please
I dont think the ELEMENT REFERENCES you are talking about exists in postgres yet. I tried to create a table using ELEMENT REFERENCES and it did'nt work
and for your answer i got this error { "name": "error", "length": 144, "severity": "ERROR", "code": "42P08", "detail": "text versus integer", "position": "61", "file": "parse_param.c", "line": "221", "routine": "variable_coerce_param_hook" }
I have written ::TEXT[] just for example purpose. You will have to put respective data type for that column. i.e. what type of data your array contains. For example if it contains array of UUID's then it should be ::UUID[]
sorry my bad i changed it to integer even though it says You will need to rewrite or cast the expression :sad:
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.