laracasts / Lets-Build-a-Forum-in-Laravel

http://laracasts.com/series/lets-build-a-forum-with-laravel
915 stars 309 forks source link

Too many queries for deleting threads and replies altogether #33

Open Mecit opened 7 years ago

Mecit commented 7 years ago

In the boot method of the Thread model, the $thread->replies->each->delete() part produces too many queries which gives rise to performance issues especially when a thread has too many replies. When you call each, it runs three query for deleting each reply (one to select thread, one to decrease the replies_count field on the threads table, one to actually delete the reply). Wouldn't calling $thread->replies()->delete() be a better approach? i.e.

    static::deleting(function ($thread) {
        $thread->replies()->delete();
    });