#postgresql-9.5
#postgresql-9.5
Вопрос:
тип мета-столбца jsonb
Json перед обновлением:
{
"state": "order.cart_finalization",
"comments": [{
"first_item": "hello"
}]
}
Мне нужно добавить новый элемент в массив (комментарии).
Новый элемент массива:
{ "second_item": "hello2"}
Я пытаюсь это:
UPDATE copy_shop_order SET meta = (
CASE
WHEN meta #>>'{comments}' IS NULL THEN jsonb_set(meta, '{comments}', '[{ "first_item": "hello"}]')
ELSE meta #>'{comments}' || '{ "second_item": "hello2"}'
END
) WHERE id = 100;
Но результат:
[
{
"first_item": "hello"
},
{
"second_item": "hello2"
}
]
Но мне это нужно:
{
"state": "order.cart_finalization",
"comments": [{
"first_item": "hello"
}, {
"second_item": "hello2"
}]
}
Ответ №1:
Вам нужно использовать jsonb_set()
update copy_shop_order
SET meta = case
when meta ? 'comments' then jsonb_set(meta, '{comments}', meta -> 'comments' || '{"second_item": "hello2"}')
else jsonb_set(meta, '{comments}', '[{ "first_item": "hello"}]')
end;