1

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
                    })
}
student
  • 13
  • 3
  • 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) – hadi purnomo Jan 18 '23 at 09:27

2 Answers2

0

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

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>
Debug Diva
  • 26,058
  • 13
  • 70
  • 123