简体   繁体   English

Postgres更新JSONB字段

[英]Postgres update jsonb fields

I have a table "profile" with a jsonb field called "payment_methods". 我有一个表“ profile”,其中包含一个名为“ payment_methods”的jsonb字段。 The jsonb field structure is this: jsonb字段结构是这样的:

[{"name": "paypal", "primary": false}, 
 {"name": "braintree", "primary": true}, 
 {"name": "skrill", "primary": false}]

I want to make a query to dynamically set the primary payment method to the method that user will choose. 我想查询以将主要付款方式动态设置为用户选择的方式。 If the user choose the paypal method as primary, i want to set the jsonb field like this: 如果用户选择paypal方法作为主要方法,则我想像这样设置jsonb字段:

[{"name": "paypal", "primary": true}, 
 {"name": "braintree", "primary": false}, 
 {"name": "skrill", "primary": false}]

So, i want to update the paypal's primary filed to true and any other payment method's primary field to false. 因此,我想将Paypal的主字段更新为true,并将其他任何付款方式的主字段更新为false。

Notice: I want to filter with the name field. 注意:我想使用名称字段进行过滤。 So if user give me for example paypal i want to set it as primary. 因此,如果用户给我例如贝宝,我想将其设置为主。

How can i do that? 我怎样才能做到这一点?

Not entirely sure of the structure of this table but I came up with this. 不能完全确定此表的结构,但我想出了这一点。

CREATE OR REPLACE FUNCTION func_updatePrimaryPaymentMethod(userid integer, pay_method_name text)
RETURNS SETOF profile
AS $$
DECLARE
    rec record;
BEGIN
    SELECT * INTO rec FROM profile WHERE id = userid;

    FOR i IN array_lower(rec.payment_methods, 1) .. array_upper(rec.payment_methods, 1)
    LOOP
        IF rec.payment_methods[i]->>'name' = pay_method_name
        THEN
            rec.payment_methods[i] := rec.payment_methods[i] || jsonb_build_object('primary', TRUE);
        ELSE
            rec.payment_methods[i] := rec.payment_methods[i] || jsonb_build_object('primary', FALSE);
        END IF;
    END LOOP;
    RETURN NEXT rec;
END;
$$  LANGUAGE PLPGSQL;

If this is a solution, I would recommend changing this design if you have the option to as this will always be hard to work with. 如果这是一个解决方案,建议您更改此设计(如果可以选择的话),因为这总是很难使用。 You shouldn't have multiple jsonb objects stored in one field. 您不应在一个字段中存储多个jsonb对象。

Why not just have the name and primary as their own columns? 为什么不只将nameprimary列作为自己的列?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM