I select some tables with json_agg and json_build, all works but I got some data that I dont want it,
My product_media (pm) is empty there are no images, if I use json_agg(json_build_object)) then I got 3x times all rows with null like this:
product_media: [
{
id: null,
src: null,
alt: null,
s_position: null,
updated_at: null
},
{
id: null,
src: null,
alt: null,
s_position: null,
updated_at: null
},
{
id: null,
src: null,
alt: null,
s_position: null,
updated_at: null
}
],
how can I say when id is null then dont show it or when no product media was found then make an empty array ?
code:
SELECT
p.id,
p.shop_id,
p.provider_id,
p.name,
p.status,
json_agg(json_build_object(
'id', pt.id,
'tag', pt.tag
)) AS tags,
json_agg(json_build_object(
'id', pm.id,
'src', pm.src,
'alt', pm.alt,
's_position', pm.s_position,
'updated_at', pm.updated_at
)) AS product_media
po.id as po_id,
po.name,
po.position,
pov.id as pov_id,
pov.value,
pv.id as pv_id,
pv.quantity,
pv.price,
pv.is_male,
pv.shipping_price,
pv.grams,
pv.weight,
pv.weight_unit,
pv.length,
pv.s_position,
pv.option_1,
pv.option_2,
pv.option_3
FROM product p
LEFT JOIN product_media pm
ON pm.p_id = p.id
LEFT JOIN product_options po
ON po.p_id = p.id
LEFT JOIN product_options_value pov
ON pov.p_o_id = po.id
LEFT JOIN product_tags pt
ON pt.p_id = p.id
LEFT JOIN product_variants pv
ON pv.p_id = p.id
WHERE p.provider_id = $1
GROUP BY
p.id,
pm.id,
po.id,
pov.id,
pv.id
LIMIT 1;
I am very thankful for your help I dont know what to do or how to do it
2
Answers
this should do the trick
This will check if
pm.id
isNUL
L, and if so returnNULL
instead of building theJSON
object.Try using
json_strip_nulls()
:If you can work with
jsonb
instead ofjson
, that would be preferred (more space efficient). If you choose to usejsonb
, then you can usejsonb_strip_nulls()
instead.