Answer the question
In order to leave comments, you need to log in
How to replace whereHas because it is too slow?
Now there is this code that displays all the articles in the desired category:
$articles = Article:with('types')->whereHas('categories', function ($query) use ($name) {
$query->where('name', $name);
})->paginate(10);
Answer the question
In order to leave comments, you need to log in
If you think about it, two simple and fast queries are better than one heavy one.
In any case, I think you will still need the category / s separately in the template somewhere, so you can first get it / them by name, and then get the articles
$categories = Category::whereName($name)->get();
$articles = Article:with('types')->whereIn('id', $categories->pluck('id'))->paginate(10);
whereHas makes the usual exists. It's not even close to being slow. The problem is the lack of indexes (on categories.name and on columns linking two tables).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question