简体   繁体   中英

Laravel 9 Eloquent

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?

This is the db screen: 在此处输入图像描述

You have to create new model instance in loop.

$new_orders_details = new OrderSDetail();

Since I cannot comment, can you try this solution?

$ordersDetail = new OrderSDetail();

$ordersDetail->insert([ //your data here]);

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

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