Laravel:将查询结果存储在变量中,然后能够使用该变量再次查询

问题描述 投票:0回答:1

我在(错误地)在

foreach
循环内生成查询时面临挑战。问题是每次循环运行时都会查询
Logs
。目前的代码如下所示:

$logs = Logs::query(); // This table has about 100,000 rows

foreach ($data as $indiv_data) {

   $checkIfDataMatches = $logs->where('employee_id', '=', $indiv_data->employee_id)->first();

   if ($checkIfDataMatches === null) {

     // Not found

   }   

   else {
   
     // Found

   }

}

上面的代码意味着多次重复读取100,000行的表。

有没有办法只获取一次

Logs
,将集合存储到变量
$logs
,然后通过查询
foreach
$logs
循环中获取数据?如果是,任何有关如何操作的帮助将不胜感激。谢谢!

php laravel
1个回答
0
投票

您应该首先获取所有员工 ID,然后将它们设置为数组,以便使用 whereIn 方法查询它们:

$employeeIds = collect($indiv_data)->pluck('employee_id')->unique()->toArray();

//注意,如果 $indiv_data 已经是一个集合,那么你不需要collect方法。

$allLgos= Logs::query()->whereIn('employee_id', $employeeIds)
    ->get();

现在您拥有 $indiv_data 中存在的员工的所有日志

请注意,如果结果尺寸较大,您可以分块...

© www.soinside.com 2019 - 2024. All rights reserved.