Darren rogers
Darren rogers

Reputation: 627

Loop insertion into table using Knex

I have a users table

 id | firstName | lastName 
---------------------------
 2  | Dave      | Smith
 3  | Peter     | Smith
 4  | Steve     | Smith

and a settings table

 id |  key    | value | user_id
--------------------------------
 1  | 'style' | 1     | 2

I want to create new rows in the settings table for each new row it should have the key = 'styleId', value = 1 and user_id = the current value of id in the loop

 id  |  key    | value | user_id
---------------------------------
 101 | 'style' | 1     | 1
 102 | 'style' | 1     | 2
 103 | 'style' | 1     | 3

pseudocode

const usersIds = knex.select('id').from('users')
for each (id in usersIds) {
    knex('settings').insert({
        value: 'style',
        key:1,
        user_id: id
    })
}

How can I do this in knex

Upvotes: 1

Views: 640

Answers (1)

Lucas Araujo
Lucas Araujo

Reputation: 1688

You don't need to make multiple insert queries here, you can first create the array of data, then make an insert query with that array.

Example:

knex.select('id').from('users').then(users => {
    const settings = []
    users.forEach(user => {
        settings.push({
            value: 'style',
            key: 1,
            user_id: user.id
        })
    })

    return knex('settings').insert(settings)
})

Upvotes: 1

Related Questions