mercredi 12 septembre 2018

Optimise database query to avoid memory issues

I have a huge Users table (maybe around 4M rows) and I want to run a monthly Job for checking their last login date and if they have not logged in update user and update isPassive column with true.

$users = \DB::table('users')
                   ->whereNull('isPassive')->get();
foreach($users as $user)
{
   if(!$user->wasActive())
   {
      $this_user = (new User)::where('id', $user->id)->first();
      $this_user->isPassive = true;
      $this_user->save();
   }
}

I have learned to run jobs with Laravel but this gives me memory issues. Well I can increase the server memory but from what I have read here, increasing the memory is not always the best solution.

I tried the chunk results but when I use where() it just hangs. If I use it without and conditions it works nice though.

I am wondering how would a experienced developer would break this job to use less memory?

Labelled it as Laravel but this is a question for any new programmer may face when learning better manage the memory.

Thanks for any advice



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2x6umbz
via IFTTT

Aucun commentaire:

Enregistrer un commentaire