Azoruk
1 month ago
1113
3
Requests

How many queries is too many?

Posted 1 month ago by Azoruk

I have a laravel website that lists "submissions" much like reddit. I use this example to more easily understand this problem.

When a user visits the home page, for example, he'll see 30 submissions listed.

Each submission represents a lot of information. Sure there's information from the submission itself, like the title and whatnot. But there's things like "save". For each submission, there must be a query to see if that user hasn't saved the submission, or else it would display "unsave".

Blade:

@if (!Auth::user()->hasSavedSubmission($submission))
    <a href="{{ route('save.submission', ['ID' => $submission->id, 'token' => $submission->token]) }}">Save</a>
@else
    <a href="{{ route('unsave.submission', ['ID' => $submission->id, 'token' => $submission->token]) }}">Unsave</a>                     
@endif

User Model:

 public function hasSavedSubmission(Submission $submission) {
    return (bool) $submission->savedSubmissions->where('user_id', $this->id)->count();
}   

Which then requires a query. But there isn't just hasSavedSubmission, there's a query to see if the user has upvoted/downvoted a submission, or whether or not they've subscribed to that sub.

It gets even worse on comment pages. Let's say I load a comments page with 200 comments. Well, to see if you've saved a comment or voted on a comment, that's 2 queries per comment, making it a total of 400 queries.

Is this normal? Is this good practice, or should I be optimizing this somehow to reduce queries, and how?

Please sign in or create an account to participate in this conversation.