Home > Blockchain >  How insert data array of object to db
How insert data array of object to db

Time:01-18

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
                    })
}

CodePudding user response:

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)

CodePudding user response:

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 >
  <table id="example"  width="100%">
    <thead>
      <tr>
        <th>Name</th>
        <th>Color</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
</div>

  • Related