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

Posted

技术标签:

【中文标题】如何在laravel中插入多条记录而不循环【英文标题】:How to insert multiple record without loop in laravel 【发布时间】:2021-01-29 22:33:59 【问题描述】:

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

$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');
    

【问题讨论】:

【参考方案1】:

这个怎么样:

$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 数组是否正常。

【讨论】:

给出这个错误Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given, called in /var/www/html/coldxlogistics/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php on line 869 你能在 InvoiceCharge::create($consignment_data) 之前 dd($consignment_data); 你的方法是正确的但是需要使用insert而不是create【参考方案2】:

如果你想节省时间,但可以给更多内存,可以使用Cursor

光标:您将使用 PHP 生成器逐一搜索您的查询项目。 1)花费更少的时间 2)使用更多的内存

$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

【讨论】:

以上是关于如何在laravel中插入多条记录而不循环的主要内容,如果未能解决你的问题,请参考以下文章

如何在oracle数据表中一次性插入多条记录?

Laravel,如何在 HTML 表格中输出相同 ID 的多条记录?

如何在oracle数据表中一次性插入多条记录?

JAVA中,向MYSQL插入多条数据,如何判断如果某记录已经存在就不插入

使用 Laravel 一次插入多条记录

使用while循环在表中插入多条记录[关闭]