I am really struggling how to implement requirement which is going to be best described with example. Consider everything below to be written in pseudocode although I am interested in solutions for postgres.
| id | id_for_user | note | created_by |
|---|---|---|---|
| 1 | 1 | Buy milk | 1 |
| 1 | 2 | Winter tyres | 1 |
| 1 | 3 | Read for 1h | 1 |
| 2 | 1 | Clean dishes | 2 |
| 2 | 2 | Learn how magnets work | 2 |
INSERT INTO notes VALUES (note: 'Learn icelandic', created_by: 1);
| id | id_for_user | note | created_by |
|---|---|---|---|
| 1 | 1 | Buy milk | 1 |
| 2 | 2 | Winter tyres | 1 |
| 3 | 3 | Read for 1h | 1 |
| 4 | 1 | Clean dishes | 2 |
| 5 | 2 | Learn how magnets work | 2 |
| 6 | 4 | Learn Icelandic | 1 |
INSERT INTO notes VALUES (note: 'Are birds real?', created_by: 2);
| id | id_for_user | note | created_by |
|---|---|---|---|
| 1 | 1 | Buy milk | 1 |
| 2 | 2 | Winter tyres | 1 |
| 3 | 3 | Read for 1h | 1 |
| 4 | 1 | Clean dishes | 2 |
| 5 | 2 | Learn how magnets work | 2 |
| 6 | 4 | Learn Icelandic | 1 |
| 7 | 3 | Are birds real? | 2 |
I would like to achieve something like this:
CREATE TABLE notes (
id SERIAL,
id_for_user INT DEFAULT nextval(created_by) -- Dynamic name for sequence so every user gets its own,
note VARCHAR,
created_by INT,
PRIMARY KEY(id, id_for_user),
CONSTRAINT fk_notes_created_by
FOREIGN KEY(created_by)
REFERENCES users(created_by)
);
So that user 1 sees (notice how id_for_user is just id on front end)
| id | note |
|---|---|
| 1 | Buy milk |
| 2 | Winter tyres |
| 3 | Read for 1h |
| 4 | Learn Icelandic |
And user 2
| id | note |
|---|---|
| 1 | Clean dishes |
| 2 | Learn how magnets work |
| 3 | Are birds real? |
Basically I want to have auto incremented field for each user.
I am then also probably going to query for the record by id_for_user filling create_by on backend based on which user made the request.
Is something like this even possible? What are my options? I would really like to have this logic on db level.