Reputation: 153
Users are allowed to choose a list of songs and add them to a playlist. there is a bridge table for the relationship between songs and playlists.
when the user assigns songs to a playlist, the application receives a list of the the song IDs and the playlist ID. the number of rows inserted into the bridge table is the same as the number of songs.
i can either call the query for each song (which seems inefficient, but usable) or i can formulate the query to insert all the data at once. my question is regarding formulating the query.
i have a list of song ids
[1, 2, 3, 4, 5, 6, 7,]
and a playlist id (just an int).
my sequelize query looks like this:
sequelize.query(
`INSERT INTO songsplaylistsbridge (song, playlist)
VALUES ($1, $2);`, {
bind: [songs, playlist]
}
)
i understand from Inserting multiple rows in mysql how the query should look, but i can't come up with a for-loop which will generate a usable object.
i have a list which looks like
['(1, 43)', '(2, 43)', '(3, 43)', '(4, 43)']
...etc. how do i insert these values into the query appropriately? thank you
Upvotes: 0
Views: 638
Reputation:
Don't use bind
, just compose the query text:
var values = ['(1, 43)', '(2, 43)', '(3, 43)', '(4, 43)'];
var query = "INSERT INTO songsplaylistsbridge (song, playlist) VALUES " + values.join(", ");
console.log(query);
Upvotes: 1