Home > Software engineering >  Adding multiple entries/rows with knex mysql
Adding multiple entries/rows with knex mysql

Time:10-06

I get the following data from the req.body:

{
    "user_id": "1",
    "user_name": "jkalandarov",
    "email": "[email protected]",
    "courses": [
        {
            "course_id": 1,
            "course_name": "English",
            "course_price": 265
        },
        {
            "course_id": 2,
            "course_name": "Node.js",
            "course_price": 200
        },
        {
            "course_id": 3,
            "course_name": "Backend Developement",
            "course_price": 300
        }        
    ]
}

I want to insert this data into three rows with the help of knex into mysql database table like this with a single query: enter image description here

Any ideas?

Thanks in advance!

CodePudding user response:

Assuming you already have your knex connection set up, it should simply allow you to pass an array of objects into the insert function to insert multiple rows with a single statement. https://knexjs.org/#Builder-insert

Step 1: Build an array of objects

const objectsToInsert = req.body.courses.map(course => {
    return {
        user_id: req.body.user_id,
        user_name: req.body.user_name,
        email: req.body.email,
        ...course
    }
});

Step 2: Insert them using your knex connection

await knex('your_table_name').insert(objectsToInsert);

This should insert those three rows into your table in a single query.

As this data is coming directly from the request body it is obviously also a good idea to add some validation here but that feels out of scope for your original question.

  • Related