My Db looks like this https://dbfiddle.uk/?rdbms=postgres_10&fiddle=7e0cf7ad1e5bf9f4e0321a2e5ec970f7
So
- A user can have multiple Books
- Basic one to many relationship
Lets suppose if a user updates preexisting book and adds more books too, How would i go about making a query for that ?
I did some research and came to the conclusion that either cte or function would come to my rescue.
My request body ( JSON ) data FOR PATCH QUERY would look like this
{
// user data
user_id: 1,
name : 'Ryan',
books : [
{
book_id : 1,
stock : 500
},
{
book_id : 2,
stock : 500
},
{
// this book should be added to the users_books table
name: 'My new book 1',
stock : 500
}
]
}
The postgresql update queries for the above data should look like ->
UPDATE users_books(stock) VALUES(500) WHERE user_id = 1 AND book_id 1;
UPDATE users_books(stock) VALUES(500) WHERE user_id = 1 AND book_id 2;
INSERT INTO users_books(user_id,book_id,stock) VALUES(1,3,500);
So looking at the structure above , i need the books_users table to updated accordingly.
My current understanding is pass the books object as jsonb to postgresql's function. Then loop through it while updating / adding books accordingly. I'm not sure how would i go about knowing whether user already has a book or not.
How would you guys transform this request body into the aforementioned complex update query ? And would doing this in a function be transactional at all?