For example, I have a table called albums
album_id | name | description | price | release_date |
---|---|---|---|---|
1 | album1 | description1 | 10.00 | current date |
2 | album2 | description2 | 10.00 | current date |
... | ... | ... | ... | ... |
and now I have a table called songs
song_id | name | description | duration | album_id |
---|---|---|---|---|
1 | song1 | song description 1 | 180 | 1 |
1 | song2 | song description 2 | 180 | 2 |
1 | song3 | song description 3 | 180 | 2 |
1 | song4 | song description 4 | 180 | 2 |
Now, I'm trying to build an API endpoint where I return a JSON of all albums which includes a list of the songs that are included in each album.
Currently, I can do it by first getting all the albums through this:
let albums;
db.query('SELECT * FROM albums', (error, results) => {
albums = results;
}
This returns a JSON with the details of all albums. Now, I want each entry in the JSON to have a songs property which contains an array of songs that belong to that album.
To do that, I thought about doing it this way
albums = albums.forEach(album => {
let songs;
db.query('SELECT * from songs WHERE album_id = ?', [album.album_id], (error, results) => {
album.songs = results;
}
}
My expected output is a JSON of containing all the properties from the first query with an additional "songs" property that contains an array of the details of each song that is in that album.
I think this would accomplish what I am trying to do but is there a better way of doing it? I have a feeling this is not the most efficient way of doing this. I am new to relational databases so I am not sure how to do this purely off of SQL.