skip to Main Content

I’m facing a challenge in (wrongfully) generating a query inside a foreach loop. The problem is that Logs is being queried each time the loop runs. The code currently looks like this:

$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

   }

}

The code above means repeatedly fetching a table of 100,000 rows multiple times.

Is there a way to just fetch Logs once, store the collection to variable $logs, then just fetch data from the foreach loop by querying $logs? If yes, any help on how to do it would be appreciated. Thanks!

2

Answers


  1. you should first get all employee ids then set them in array to use whereIn method query for them:

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

    // notice that if $indiv_data is already a collection then you do not need collect method.

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

    now you have all Logs for employees that exists in $indiv_data

    notice that you can chunk results if they has big size …

    Login or Signup to reply.
  2. @fufubrocat, it is unclear to me based on your comment to OMR what exactly is happening. Let’s break it down.

    1. You get all $logs. Will be great to see the structure of $logs. Probably one record.
    2. You loop over employee data you are importing from a CSV
    3. What do you want $checkIfDataMatches to find from $logs?
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search