Caio Duarte
Caio Duarte

Reputation: 1

Insert Multiple Rows with Knex and PG

i've got some problem here. I have an array, and i need to insert or update the records on my database.

I got this test table with two fields: ID and TEAM.

This is my code:

var idPlayer = []
query('tb_teste').select('id')
  .then((row) =>{

    for(var i = 0; i < row.length; i++){
      idPlayer[i] = row[i].id
    }

    // just put this here for test purposes. I have 360+ PlayerIDs.
    var pArray = [{ PlayerID: 201980, TeamID: 1610612761 },
                  { PlayerID: 202691, TeamID: 1610612744 }]

    for(var x = 0; x < pArray.length; x++){
        if(idPlayer.includes(pArray[x].PlayerID)){
            console.log('Está na listagem', pArray[x].PlayerID)
         // will do the update later
        } else {
            console.log('Não está na lista', pArray[x].PlayerID)
            return query('tb_teste').insert({
                        id: pArray[x].PlayerID,
                        team: pArray[x].TeamID
                })
        }
    }

  })

My table is empty right now, but i cant insert those two records, only the first one is inserted at the end. There is anyway that i can insert those records at one time? I really need to use for to do this?

Thanks in any advance.

Upvotes: 0

Views: 923

Answers (1)

Mikael Lepist&#246;
Mikael Lepist&#246;

Reputation: 19718

I suppose you might be trying to do something like this:

const pArray = [{ PlayerID: 201980, TeamID: 1610612761 },
                { PlayerID: 202691, TeamID: 1610612744 }];

query('tb_teste').then(rows => {
  console.log('all rows in table before:', rows);
  return query('tb_teste').insert(pArray).returning('*');
}).then(rows => {
  console.log('Inserted rows:', rows);
  return query('tb_teste');  
}).then(rows => {
  console.log('all rows in table after:', rows);
});

Upvotes: 1

Related Questions