I would like a function get a result look like this:
Student:
| ID | Name | ID_TEACHER |
|---|---|---|
| 1 | Jhon | 1 |
| 2 | Maria | 1 |
Teacher:
| ID | Name |
|---|---|
| 1 | Peter |
| 2 | Joseh |
Query:
select json_fk_full(t) from Student t;
Result:
{student: [{"ID":1, "Name":"Jhon", "ID_TEACHER": 1},
{"ID":1, "Name":"Jhon", "ID_TEACHER": 1}],
teacher: [{"ID":1, "Name":"Peter"}]}
You can cast whole rows to
jsonbusingto_jsonb(), or cast&aggregate them withjsonb_agg(): demo{"ID": 2, "Name": "Maria", "ID_TEACHER": 1}],
"teacher": {"ID": 1, "Name": "Peter"}}
Normally this type of
group byisn't a good idea but that's just to demonstrate how you can let Postgres automagically deduce the desiredjsonbstructure based on row type passed into these functions.I'm not sure what rules you have in mind as to how exactly you want to map these tables to the jsonb, so I went with an intuitive "one row=one teacher and all of their students". If that's not the case, you're welcome to add a correction.