php - 查询需要很长时间才能执行 laravel
问题描述
我正在上传一个 excel 文件,其中包含用户数据及其产品状态 (0,1)。
我想先将产品数据保存在 Productsale 表中,包括 user_id、product_id、target_month 和 status。
然后我获取所有用户,然后从 productsale 表中获取产品及其状态并对其进行计数并将其结果保存在 Saleproduct 表中。
我在 excel 文件中有 33000 行,在 productsale 中节省了 300k,因为每个用户都有 8 个产品,
这是我的代码
try {
$path = $request->file('file')->store('upload', ['disk' => 'upload']);
$value = (new FastExcel())->import($path, function ($line) {
$user = User::where('code', $line['RVS Code'])->first();
$store = Store::where('code', $line['Customer Code'])->first();
$a = array_keys($line);
$total_number = count($a);
$n = 4;
$productsale= 0;
for ($i=3; $i<$total_number; $i++) {
$str_arr = preg_split('/(ml )/', $a[$i]);
$product = Product::where('name', $str_arr[1] ?? null)->where('type', $str_arr[0] . 'ml')->first();
if (!empty($product)) {
$product = ProductSale::updateOrCreate([
'user_id' => $user->id,
'store_id' => $store->id,
'month' => $line['Target Month'],
'product_id' => $product->id,
'status' => $line[$str_arr[0] . 'ml ' . $str_arr[1]],
]);
}
}
});
//sales
$datas = User::all();
foreach($datas as $user){
$targets = Target::where('user_id',$user->id)->get();
foreach($targets as $target){
$sales = Sales::where('user_id', $user->id)->where('month',$target->month)->first();
$products = Product::all();
foreach ($products as $product) {
$totalSale = ProductSale::where('user_id',$user->id)->where('month',$target->month)->where('product_id',$product->id)->sum('status');
$sale_product = SalesProduct::updateOrCreate([
'product_id' => $product->id,
'sales_id' => $sales->id,
'sale' => $totalSale,
]);
}
}
}
return response()->json(true, 200);
}
解决方案
如果运行时间过长(并且可能导致返回错误),则不要同步执行 - 即。而用户正在等待 - 但它是异步的。
您的控制器应该只关心验证文件,将其保存到存储中,并将成功代码返回给用户,告诉他们文件已上传,并将很快处理。
然后将有关文件处理的所有代码移动到控制器调度的作业中,该作业在后台运行。理想情况下,这将在队列中(在这种情况下,请查看您的队列设置,因为默认值为 30 秒以使作业在那里完成,这与您可能已经犯规的 PHP 设置一致,因此请准备好允许作业执行的时间更长)。
推荐阅读
- java - 内部类可见性的一些问题
- android - 如何使用android中的任何布局将两个文本视图与背景水平对齐?
- image - 执行“docker save”时出错:open.docker_temp_186536267:只读文件系统
- slurm - 错误时自动重新运行使用 sbatch --array 提交的作业
- python - Python:使用地图功能打印元素
- .net - 如何在 Xml 中获取 AppData 目录
- python - 继续接收:TypeError:不支持的操作数类型*:来自python的'NoneType'和'int'
- vue.js - 嵌套 v-for 中的增量计数器
- c# - 动态更改所选字节的掩码
- html - 提交html表单时,不打开新页面但显示弹出窗口