【问题标题】:How to insert multiple record without loop in laravel如何在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');
    }

【问题讨论】:

    标签: laravel laravel-5 eloquent query-builder


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 2018-12-03
      相关资源
      最近更新 更多