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
you should first get all employee ids then set them in array to use whereIn method query for them:
// notice that if $indiv_data is already a collection then you do not need collect method.
now you have all Logs for employees that exists in $indiv_data
notice that you can chunk results if they has big size …
@fufubrocat, it is unclear to me based on your comment to OMR what exactly is happening. Let’s break it down.
$logs
. Will be great to see the structure of$logs
. Probably one record.$checkIfDataMatches
to find from$logs
?