Adding multiple entries/rows with knex mysql

I get the following data from the req.body:

{
    "user_id": "1",
    "user_name": "jkalandarov",
    "email": "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e54555f525f505a5f4c51487e59535f5752105d5153">[email protected]</a>",
    "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:
Adding multiple entries/rows with knex mysql

Any ideas?

Thanks in advance!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x