Du kan generere JSON-indhold direkte fra MySQL. Her er en løsning, der fungerer med MySQL 5.7 eller højere.
Som en starter kan du overveje funktion JSON_OBJECT()
, der genererer et JSON-objekt for hver post i tabellen:
SELECT
p.*,
JSON_OBJECT('id', id, 'project_name', project_name, 'parent_id', parent_id) js
FROM tbl_projects p;
Givet dine eksempeldata returnerer dette:
| 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"} |
For at generere dit forventede output, vil vi selv-JOIN
tabellen for at finde børneposter og bruge aggregatfunktion JSON_ARRAYAGG()
for at generere det indre JSON-array. Et ekstra niveau af aggregering fylder alt i et enkelt objekt. Som vist i dine eksempeldata antog jeg, at rodprojekter har parent_id = 0
og at der kun er ét niveau af hierarki:
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
Udbytter:
| 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"}]} |