I am working on a site where users can trade items with other users. Upon completion of a trade, I need to change the owner of the items.
My 'items' table has a foreign key referencing the user. Given two item id's, how can I switch the foreign keys with each other?
I've tried something like this...
UPDATE items
SET user_id = (
SELECT users.id FROM items
INNER JOIN users
ON users.id = items.user_id
WHERE items.id = $1
)
WHERE id = $2;
UPDATE items
SET user_id = (
SELECT users.id FROM items
INNER JOIN users
ON users.id = items.user_id
WHERE items.id = $2
)
WHERE id = $1;
This doesn't work because after the first UPDATE is performed, the user_id is updated, so the second SELECT statement does not work as intended.