简体   繁体   中英

How insert data array of object to db

I want to insert the data like below:

"car" : [
       {
         "name": "toyota",
         "color": "red",
       },
       {
         "name": "hyundai",
         "color": "black",
       },
       {
         "name": "honda",
         "color": "grey",
       }
    ]

to database using adonis which is.ts, specifically in table cars with variable id, car_name, car_color. And I do this:

var i
for(i = 0; i<car.length; i++){
    await Database .table('cars')
                   .insert({
                      car_name: car[i].name,
                      car_color: car[i].color
                    })
}

First you need to re mapping array data before insert. for example:

const newCar = car.map(objCar => ({ car_name: objCar.name, car_color: objCar.color }))

then you can use multiInsert in adonis like bellow.

await Database.table('cars').multiInsert(newCar)

You can achieve this by using data property in the initialization object.

Live Demo :

 const car = [ { "name": "toyota", "color": "red", }, { "name": "hyundai", "color": "black", }, { "name": "honda", "color": "grey", } ]; $('#example').DataTable({ "data": car, "columns": [ { "data": "name" }, { "data": "color" } ] });
 <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script> <link href="https://cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" /> <script src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script> <div class="container"> <table id="example" class="display" width="100%"> <thead> <tr> <th>Name</th> <th>Color</th> </tr> </thead> <tbody> </tbody> </table> </div>

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