Hello i'm trying to use eloquent in my code:
$nr_riga = 0;
foreach($data_detail as $key => $row_detail) {
$nr_riga = $key 1;
$new_orders_details->nr_riga = $nr_riga;
$new_orders_details->codice_articolo = $row_detail['codice_articolo'];
$new_orders_details->quantita = $row_detail['quantita'];
$new_orders_details->prezzo = $row_detail['prezzo'];
$new_orders_details->order_id = $new_orders_grid->id;
$new_orders_details->save();
// DB::table('orders_detail')->insert([
// 'order_id' => $new_orders_details->order_id,
// 'nr_riga' => $nr_riga,
// 'codice_articolo' => $new_orders_details->codice_articolo,
// 'quantita' => $new_orders_details->quantita,
// 'prezzo' => $new_orders_details->prezzo,
// ]);
}
This loop works both ways but not equally.. when i use $new_orders_details->save(); it inserts to the db a single row,seems to not looping.
DB::table('orders_detail')->insert does the job as i want.
How to convert it to eloquent for have same result?
CodePudding user response:
You have to create new model instance in loop.
$new_orders_details = new OrderSDetail();
CodePudding user response:
Since I cannot comment, can you try this solution?
$ordersDetail = new OrderSDetail();
$ordersDetail->insert([ //your data here]);
CodePudding user response:
I think you can prepare date in loop and make one batch insert using Model::insert($your_data)
Saving in loop it is not best way to save data to db Like:
$data = [];
foreach($data_detail as $key => $row_detail) {
$nr_riga = $key 1;
$data[]['nr_riga'] = $nr_riga;
$data[]['codice_articolo'] = $row_detail['codice_articolo'];
$data[]['quantita'] = $row_detail['quantita'];
$data[]['prezzo'] = $row_detail['prezzo'];
$data[]['order_id'] = $new_orders_grid->id;
}
NewOrderDetails::insert($data);
It is save all you data with using model