[英]PostgreSQL Array inside a JSON object
Im trying to build a custom json, from two tables with left join on a PostgreSQL function, but cant it working. 我正在尝试从两个具有左连接的表构建一个自定义json,但PostgreSQL函数无法正常工作。
Table Structure: 表结构:
post 发布
id | title | description
postPhoto postPhoto
id | postId (FK) | name
json example: json示例:
{
postId: 1,
title: ''
description: '',
postPhotos: [
{id: 1, name: 'photo1.png'},
{id: 1, name: 'photo2.png'},
]
}
SQL Function: SQL函数:
$BODY$DECLARE
success boolean;
msg text;
var_most_recent json;
BEGIN
SELECT to_json(array_agg(t)) INTO var_most_recent FROM (
SELECT *
( SELECT to_json(array_agg(t)) FROM (
SELECT * FROM postPhoto AS PP WHERE post.id = PP."postId"
)t )
FROM post
ORDER BY id DESC LIMIT 10
)t;
success = TRUE; msg = 'Successfully Returned Post data';
RETURN (SELECT json_build_object(
'success', success,
'msg', msg,
'body', json_build_object(
'mostRecent', var_most_recent
)
));
END;$BODY$
I think you are missing the json_agg
aggregate function. 我认为您缺少
json_agg
聚合函数。 Here's how I would do it: 这是我的处理方式:
SELECT json_agg(p)
FROM
(SELECT
json_build_object(
'postId', post.id,
'title', post.title,
'description', post.description,
'postPhotos',
(SELECT json_agg(json_build_object('id',id,'name',name))
FROM postPhoto WHERE postId=post.id)
) AS p
FROM post
ORDER BY post.id
LIMIT 10) as t
WHERE json_array_length(p->'postPhotos')>1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.