如何在 laravel 中不循环地插入多条记录

How to insert multiple record without loop in laravel

我需要在数据库中插入多条记录。目前我正在插入循环,当记录很大时会导致超时。有什么方法可以不使用循环吗?

$consignments =   Consignment::select('id')->where('customer_id',$invoice->customer_id)->doesntHave('invoice_charges')->get();
       foreach($consignments as $consignment){
         InvoiceCharge::create(['invoice_id'=>$invoice->id,'object_id'=>$consignment->id,'model'=>'Consignment']);
       }

寄售在模型

中有hasOne关系
public function invoice_charges()
    {
        return $this->hasOne('App\Models\Admin\InvoiceCharge', 'object_id')->where('model', 'Consignment');
    }

这个怎么样:

$consignments = Consignment::select('id')->where('customer_id',$invoice->customer_id)->doesntHave('invoice_charges')->get();
       foreach($consignments as $consignment){
         $consignment_data[] = ['invoice_id'=>$invoice->id,'object_id'=>$consignment->id,'model'=>'Consignment'];
       }
InvoiceCharge::insert($consignment_data);

通过这种方式,您可以通过一个查询而不是循环输入。只需检查 consignment_data 数组是否正常。

如果想节省时间,又能多留点记忆,可以用Cursor,

Cursor: You will use PHP Generators to search your query items one by one. 1)It takes less time 2) Uses more memory

$consignments =   Consignment::select('id')->where('customer_id',$invoice->customer_id)->doesntHave('invoice_charges')->cursor();
       foreach($consignments as $consignment){
         InvoiceCharge::create(['invoice_id'=>$invoice->id,'object_id'=>$consignment->id,'model'=>'Consignment']);
       }

可以参考here