U kunt JSON-inhoud rechtstreeks vanuit MySQL genereren. Hier is een oplossing die werkt met MySQL 5.7 of hoger.
Als een starter, coonsider functie JSON_OBJECT()
, dat een JSON-object genereert voor elk record in de tabel:
SELECT
p.*,
JSON_OBJECT('id', id, 'project_name', project_name, 'parent_id', parent_id) js
FROM tbl_projects p;
Gezien uw voorbeeldgegevens, retourneert dit:
| id | project_name | parent_id | js |
| --- | ------------------- | --------- | ---------------------------------------------------------------- |
| 1 | Carmichael House | 0 | {"id": 1, "parent_id": 0, "project_name": "Carmichael House"} |
| 2 | Carmichael Kitchen | 1 | {"id": 2, "parent_id": 1, "project_name": "Carmichael Kitchen"} |
| 3 | Carmichael Bathroom | 1 | {"id": 3, "parent_id": 1, "project_name": "Carmichael Bathroom"} |
| 4 | Dowd Apartment | 0 | {"id": 4, "parent_id": 0, "project_name": "Dowd Apartment"} |
| 5 | Dowd Kitchen | 4 | {"id": 5, "parent_id": 4, "project_name": "Dowd Kitchen"} |
Om uw verwachte output te genereren, zullen we zelf-JOIN
de tabel om onderliggende records te vinden en gebruik aggregatiefunctie JSON_ARRAYAGG()
om de binnenste JSON-array te genereren. Een extra aggregatieniveau stopt alles in een enkel object. Zoals blijkt uit uw voorbeeldgegevens, ging ik ervan uit dat rootprojecten parent_id = 0
. hebben en dat er maar één hiërarchieniveau is:
SELECT JSON_OBJECT('projects', JSON_ARRAYAGG(js)) results
FROM (
SELECT JSON_OBJECT(
'id', p.id,
'project_name', p.project_name,
'parent_id', p.parent_id,
'children', JSON_ARRAYAGG(
JSON_OBJECT(
'id', p1.id,
'project_name', p1.project_name,
'parent_id', p1.parent_id
)
)
) js
FROM tbl_projects p
LEFT JOIN tbl_projects p1 ON p.id = p1.parent_id
WHERE p.parent_id = 0
GROUP BY p.id, p.project_name, p.parent_id
) x
Opbrengsten:
| results |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| {"projects": [{"id": 1, "children": [{"id": 2, "parent_id": 1, "project_name": "Carmichael Kitchen"}, {"id": 3, "parent_id": 1, "project_name": "Carmichael Bathroom"}], "parent_id": 0, "project_name": "Carmichael House"}, {"id": 4, "children": [{"id": 5, "parent_id": 4, "project_name": "Dowd Kitchen"}], "parent_id": 0, "project_name": "Dowd Apartment"}]} |