I have three tables: person, pet, pup.
A person can have many pets. A pet can have many pups.
I build my schema and insert data like this:
create table person (
id serial primary key,
name text
);
create table pet (
id serial primary key,
owner int,
name text
);
create table pup (
id serial primary key,
parent int,
name text
);
insert into person (name) values
('tom'), ('dick'), ('harry');
insert into pet (owner, name) values
(1, 'fluffy'),
(2, 'snuffles'),
(1, 'mr potato head');
insert into pup (parent, name) values
(1, 'fluffy jr'),
(1, 'fluffy II');
we see person "tom" has two pets "fluffy" and "mr potato head". we see person "dick" has one pet "snuffles".
we see pet "fluffy" has two pups "fluffy jr" and "fluffy II".
I am trying to get a doubly nested array, but I can only get one level of nesting. Here is my sql fiddle - http://sqlfiddle.com/#!17/03659/2 and they query i use:
select p.*,
array_agg(row_to_json(
pet
)) filter (where pet.id is not null) as pets
from person p
left outer join pet pet
on pet.owner = p.id
group by p.id;
What I am hoping for is for entry for "tom" to be doubly nested for "pups":
{
"id": 1,
"name": "tom",
{
"id": 1,
"owner": 1,
"name": "fluffy",
"pups": [
{
"id": 1,
"parent": 1,
"name": "fluffy jr"
},
{
"id": 2,
"parent": 1,
"name": "fluffy II"
}
]
}
}
Anyone know how to get this double nesting?