繁体   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