Sql querying multiple objects
Unanswered
Rex posted this in #help-forum
RexOP
I have 3 tables in my sql db:
Fruit
Vegetables
Pasta
In every table there's a PK and 2 FK, one for user and another one for a category.
How can I get a JSON like this:
{
"fruit: [ {}, {} ],
"vegetables: [ {}, {} ],
"pasta: [ {}, {} ],
}
Fruit
Vegetables
Pasta
In every table there's a PK and 2 FK, one for user and another one for a category.
How can I get a JSON like this:
{
"fruit: [ {}, {} ],
"vegetables: [ {}, {} ],
"pasta: [ {}, {} ],
}
2 Replies
Your not giving us mush context to work with but if you are looking for an sql query here is one that should work.
SELECT json_agg(to_json(f)) AS fruits FROM Fruit f;
SELECT json_agg(to_json(v)) AS vegetables FROM Vegetables v;
SELECT json_agg(to_json(p)) AS pasta FROM Pasta p;@Pearls Your not giving us mush context to work with but if you are looking for an sql query here is one that should work.
sql
SELECT json_agg(to_json(f)) AS fruits FROM Fruit f;
SELECT json_agg(to_json(v)) AS vegetables FROM Vegetables v;
SELECT json_agg(to_json(p)) AS pasta FROM Pasta p;
RexOP
Yes I'm sorry, this is the schema:
User is from Clerk, so I just have the reference to the string.
And I would like to put all this objects in only 1 JSON, so just 1 query, and this in return:
{
"fruit: [ {id: 1, title: "apple", created_at: "12:02:24 12-20-04" }, {} ],
"vegetables: [ {}, {} ],
"pasta: [ {}, {} ],
}
model Category {
id Int @id @default(autoincrement())
title String
description String
color String
user_id String
fruits Fruit[]
vegetables Vegetable[]
pastas Pasta[]
}
model Fruit {
id Int @id @default(autoincrement())
title String
created_at DateTime
user_id String
category_id Int
category Category? @relation(fields: [category_id], references: [id])
}
model Vegetable {
id Int @id @default(autoincrement())
title String
created_at DateTime
user_id String
category_id Int
category Category? @relation(fields: [category_id], references: [id])
}
model Pasta {
id Int @id @default(autoincrement())
title String
created_at DateTime
user_id String
category_id Int
category Category? @relation(fields: [category_id], references: [id])
}User is from Clerk, so I just have the reference to the string.
And I would like to put all this objects in only 1 JSON, so just 1 query, and this in return:
{
"fruit: [ {id: 1, title: "apple", created_at: "12:02:24 12-20-04" }, {} ],
"vegetables: [ {}, {} ],
"pasta: [ {}, {} ],
}