I recently started learning postgresql, and I had a little problem setting up relationships between tables.
I have 2 tables – users and projects. Each project has its creator (user), and each user has an array with his projects.
create TABLE users(
id SERIAL PRIMARY KEY,
name VARCHAR(200) UNIQUE,
email VARCHAR(1000) UNIQUE,
password VARCHAR,
tags VARCHAR[],
about VARCHAR(2000),
socials VARCHAR[],
projects VARCHAR[], //array of projects
avatarurl VARCHAR,
)
create TABLE projects(
id SERIAL PRIMARY KEY,
title VARCHAR(200),
text VARCHAR(3000),
needs VARCHAR[],
socials VARCHAR[],
creator_id INTEGER FOREIGN KEY (creator_id) REFERENCES users(id),
)
I need that when creating a new project, its ID is automatically added to the array of user projects. How can this best be achieved?
2
Answers
As it turned out, storing foreign keys in an array is not the best idea; everything could have been done much simpler by simply leaving the foreign key to the user in the project that he created.
As for the speed of searching in the table, as far as I understand, PostgresSCL has already taken care of this.
That is a classical many to many relationship which requires a third table since a
user
may be in 0 or manyprojects
and aproject
may have 0 or manyusers