I needed to update all of my users with some settings in a new table.
I wrote this:
$users = User::all();
foreach($users as $u) {
$settings = Settings::query()->where('user_id', $u->id)->doesntExist();
if ($settings) {
$s = new Settings();
$s->user_id = $u->id;
$s->show_alltime_stats = 1;
$s->show_time_listened = 1;
$s->save();
}
}
What I'm trying to do is
- Get all users from users table.
- Check if they exist in the settings table.
- If they don't exist, add them.
Now This was quick and dirty and I didn't use a queue or jobs or anything. just ran this as you see it.
Strange thing after several seconds the page times out, but I noticed the query keeps going. Whats even worse is it took me a few goes to realise this, so users are being created in the settings table multiple times.
Could someone explain to me what madness is going on here? I mean even IF the script were to keep running, I would have thought my code would prevent users being added multiple times.
Any and all help appreciated. I'd like to understand what I've done.