I discovered that the dev team on my project writes a database query that takes a long time to return results (average about 58 seconds for a query like this):
select `id`, `name`, `slug`, `source_id`, `status`, `author_id`, `total_words`, `view`, `cover`, `desc`,
(select count(*) from `transactions` where `stories`.`id` = `transactions`.`story_id`) as `transactions_count`
from `stories` where `display` = 1 and
exists (select * from `categories` inner join `story_categories` on `categories`.`id` = `story_categories`.`category_id`
where `stories`.`id` = `story_categories`.`story_id` and `category_id` in (1, 2, 5, 9, 16, 81))
order by `transactions_count` desc limit 10;```
///////////////
Code Colltroller:
```///////////
public function stSuggestion(Request $request, Story $story)
{
$categories = $story->categories;
$categories = $categories->map(function ($item) {
return $item->id;
});
$stories = Story::select(['id', 'name', 'slug', 'source_id', 'status', 'author_id', 'total_words', 'view', 'cover', 'desc'])->with('author:id,name,slug')->withCount('transactions')
->display()
->orderBy('transactions_count', 'desc')->whereHas('categories', function (Builder $query) use ($categories) {
$query->whereIn('category_id', $categories);
})->take(10)->get();
return response()->json($stories);
}```
/////////////////////
After studying the query, I edited the query as follows:
/////////////////
```select STR.`id`, `name`, `slug`, `source_id`, `status`, `author_id`, `total_words`, `view`, `cover`, `desc`, STC.Transaction_Count
from `stories` as STR
Inner Join (Select `story_id`, count(`story_id`) as 'Transaction_Count' From transactions Group By `story_id`)
STC On STC.`story_id`= STR.`id`
Inner Join story_categories CAT On CAT.`story_id` = STR.`id`
And CAT.category_id In (1, 2, 5, 9, 16, 81)
where STR.`display` = 1
order by STC.Transaction_Count desc limit 10;```
I tried running the command on phpMyAdmin and the response time was 0.5s (too perfect compared to 58s above). But I don't know how to convert this query to Builder query to replace the query in Coltroller. Please help me.