You need to review indexes.
In your posts table make sure user_id and tag are indexed.
Hi guys, I have a significant performance issue in a simple scope. The scope uses WhereHas for a table that contains 80k records.
Let's imagine a forum has 1.000 users and 100.000 posts. I want to display all users that have posts with a 'Foo' tag.
public function scopeHasPostsWithTag(Builder $query, $tag)
{
return $query->whereHas('posts', function ($query) use ($tag) {
$query->where('tag', $tag);
})->get();
}
This query executes minutes. Sometimes it results in a timeout error. I assume it reads all 100k records for each user.
Is it possible to speed up this query?
I thought about caching the whole query, but the data always changes. I have to clear the cache after every new post.
It would be perfect to use a cached function like hasPostsWithTags($tag) for each user individually and after that build scopes based on this function. But I believe it is not possible...
How to deal with it?
@snapey @jlrdw You both saved my day!
Not sure why I included the "get()" statement (actually it paginated my results properly working as an API with a spatie query builder), but removing get() and the most important adding indexes heled a lot!
Actually, I did not use indexes before in my small projects, and I think this was a huge mistake.
Just added $table->index('tag'); to the posts table, and it worked fine.
Please or to participate in this conversation.