W
W
WAYNEDEV2021-08-25 17:01:57
PostgreSQL
WAYNEDEV, 2021-08-25 17:01:57

How to group data in postgresql?

I have two tables (one for portfolios, one for portfolio photos), how do I output an array of portfolios with their associated photos? How to build a query for SELECT?

[{ 
  name: '', descripton: '',
  ... 
  images: [{src: 'url', src_build: 'url'}, {src: 'url', src_build: 'url'}]
}]

61264d362166f301619796.png61264d480cd8c512979805.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2021-08-25
@WAYNEDEV

select 
  portfolio.id, portfolio.name,
  array_agg(json_build_object('src', photos.src, 'src_build', photos.src_build))
from portfolio
left join photos on portfolio.id = photos.portfolio_id
group by portfolio.id, portfolio.name
;

PostgreSQL fiddle

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question