0

I'm trying to insert into another table if a user has a certain role. The roles are currently stored on the user object as a json array [{'type': 'ADMIN'}]

My code is as follows

BEGIN
    IF NEW.roles->'type' @> '"ADMIN"' THEN
        // INSERT INTO new_table
    END IF;
    RETURN NEW;
END;

The row never gets inserted if the role is there. Is there a way to do IF statements on jsonb?

1 Answer 1

1

As roles is an array, you need to test for an array element:

IF NEW.roles @> '[{"type": "ADMIN"}]'

Alternatively, if you know the array only contains a single element, you can access the value by index:

IF NEW.roles -> 0 ->> 'type' = 'ADMIN'
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.