I'm writing a API for an Q&A section of a project for school. With my current schema, I have 3 tables. One for the questions, one for the answers, and one to store any image URLs for the answers.
You can take a look at the schema design here:
. You can ignore the products table as I've since revised the overall structure and am relying on the product_id to come through as a url query when hitting the API endpoint instead.
Basically, what I'm trying to accomplish is I want to query all 3 tables to get results that match down the chain of 1-to-Many for each table.
So what I want the data to ultimately look like is:
results: [
{
<data from question table>
answers: [
{
<data from answer table>
photos: [
<array of urls from photos table>
]
},
...etc
]
},
...etc
]
The logical flow would basically be as follows:
->Get all questions associated with the given product_id
->For each question, get all answers associated with it's question_id
->For each answer, get all URLs associated with the answer_id
From what I've seen in the docs for MySQL it looks like I can create JSON objects using JSON_OBJECT() but I'm not sure how to basically create a temporary "column" on the tables to get my data to look how I want it.
I'm sorry if I didn't explain too well, I'm very new to MySQL. Please leave a comment if any clarification is needed.
TL;DR: How can I structure my MySQL query to make the data that's returned become a json object on a new column that doesn't exist in the next table up the chain? Is it feasible to do that in one query? Am I better off querying each table individually and merging the results somehow?