Answer the question
In order to leave comments, you need to log in
How to simplify laravel query?
$items = DataRelationship::where('link_id', $link->id)->get()->filter(function($user) {
return (isset($user->user));
})->sortByDesc(function($item) {
return $item->club->where('status', 1)->count();
})->take(10)
Answer the question
In order to leave comments, you need to log in
Because it is necessary to do one request normally.
And you generally select everything that is possible ->get ()
And then filters begin and more subqueries, at least one for each row that was initially found in the database, one at a time. Those. 75,000 output requests, and maybe even 2 times more, taking into account the first filter.
Read the doc for with(), orderBy() and probably leftJoin() and make one normal request.
DataRelationship::select(['id', 'name', etc...])->whereLinkId($link->id)->whereHas('user')
->addSelect(
DB::raw( '(select count(id) from clubs where data_relationships.id = clubs.data_relationship_id) as clubs_count' )
)->orderBy('clubs_count', 'desc')->get();
Write a pure SQL query first and execute it directly, not from PHP. That's when you have it and will be executed for the time that suits you and will return exactly what you need, then we'll think about how to shove it into the ORM.
And so .. an empty lesson in your case.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question