0

I have json object that is structured like this

{
   item_id:"f1e00bae-40b1-4bb6-ab21-fc8b5426ad0a"
   item_amount:8978
}

now I have a function that looks something like this:

create or replace function update_item(
    update_item JSON,
    username text
)
RETURNS item
as $$
DECLARE 
inserted item;
begin
     UPDATE item
     set amount=amount+update_item.item_amount
     WHERE 
     item.owner=username
     AND
     item.id=update_item.item_id
     RETURNING * INTO inserted;

     RETURN inserted;
         
             

END $$
language plpgsql;

But it gives me this error:

missing FROM-clause entry for table "update_item"

So how can I get the required values from the JSON paramter?

0

1 Answer 1

1

You can access a key's value using the ->> operator. But as everything is "text" in JSON, you will have to cast the values when you use them:

create or replace function update_item(update_item JSON, username text)
  RETURNS item
as $$
DECLARE 
  inserted item;
begin
  UPDATE item
    set amount = amount + (update_item ->> 'item_amount')::int
  WHERE item.owner = username
  AND item.id = (update_item ->> 'item_id')::uuid
  RETURNING * INTO inserted;

  RETURN inserted;
END $$
language plpgsql;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.