簡體   English   中英

Laravel - 從請求中更新大量數據的最佳方法?

[英]Laravel - best way to update huge amount of data from request?

我有一個使用 laravel 開發的電子商務應用程序。 每天我都想從外部 api 更新一些產品(請求)。

回復:

[
  {
    "id": 1,
    "code": "0564",
    "amount": 200
  },
  {
    "id": 2,
    "code": "4235",
    "amount": 24
  },
  {
    "id": 3,
    "code": "27683",
    "amount": 646
  },
  {
    "id": 4,
    "code": "457",
    "amount": 44
  },
]

在 controller 中的 laravel function 下面:

public function import(Request $request)
    {
        $products = $request->all();

        foreach ($products as $product) {
            $currentProduct = Product::where('code', $product['code'])->first();
            if ($currentProduct) {
                $currentProduct->amount = $product['amount'];
                $currentProduct->update();
            }
        }

        return response()->json([
            'status' => 'success',
        ], Response::HTTP_OK);
}

上面的代碼可以工作,但速度較慢。 有沒有最好的方法來做到這一點?

You Can Use




       public function import(Request $request)
            {
                $products = $request->all();
        
                foreach ($products as $product) {
                 Product::where('code', $product['code'])
                ->update(['amount'=>$product['amount']]);
                }
        
                return response()->json([
                    'status' => 'success',
                ], Response::HTTP_OK);
        }

 

如果您使用的是 (Laravel >= 8.x),則有一個名為 upsert 的方法。 該方法的第一個參數包含要插入或更新的值,而第二個參數列出了在關聯表中唯一標識記錄的列。 該方法的第三個也是最后一個參數是一個列數組,如果數據庫中已經存在匹配的記錄,則應該更新這些列。

嘗試這樣的事情:

public function import(Request $request)
{
    $data = $request->all();

    foreach (array_chunk($data, 500) as $products) {
        $updateData = [];
        foreach($products as $value) {
            $currentProduct = Product::where('code', $value['code'])->first();
            if ($currentProduct) {                
                $updateData[] = [
                    'code' => $value['code'],
                    'amount' => $value['amount'],
                ];
            }
        }

        Product::upsert($updateData, ['code'], ['amount']);
    }

    return response()->json([
        'status' => 'success',
    ], Response::HTTP_OK);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM