简体   繁体   中英

inserting multiple rows into mysql inside web application

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

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM