基本的な考え方は、クエリはjsonが特定の方法で構造化されていることを期待する必要があるということです。そうしないと、非常に複雑になります。期待される構造に基づいて、json_to_recordset
を使用してjson構造を列に分解できます。 json_build_object
を使用して追加情報で再構築します およびjson_agg
。
WITH tab_properties_with_expanded_data_type AS (
SELECT
content_type.id AS content_type_id,
tab.name AS tab_name,
json_agg(
-- re-build the property object, but with additional data_type information
json_build_object(
'name', property.name,
'order', property.order,
'help_text', property.help_text,
'description', property.description,
'data_type', json_build_object('id', data_type.id, 'html', data_type.html)
)
) AS tab_properties
FROM content_type,
json_to_recordset(content_type.tabs) AS tab(name TEXT, properties JSON),
json_to_recordset(tab.properties) AS property(name TEXT, "order" INTEGER, help_text TEXT, description TEXT, data_type INTEGER)
LEFT JOIN data_type ON data_type.id = property.data_type
GROUP BY
content_type.id,
tab.name
)
SELECT
tab_properties_with_expanded_data_type.content_type_id AS id,
json_agg(
-- rebuild the tab object
json_build_object(
'name', tab_properties_with_expanded_data_type.tab_name,
'properties', tab_properties_with_expanded_data_type.tab_properties
)
)
FROM tab_properties_with_expanded_data_type
GROUP BY
tab_properties_with_expanded_data_type.content_type_id
これは機能しますが、柔軟性の点で非常に制限されています。タブとプロパティのすべてのフィールドを明示的にリストする必要があり、ドキュメントには特定の構造があると思います。しかし、それは良いスタートです:)