N
N
Nubbin2018-06-22 17:51:18
Laravel
Nubbin, 2018-06-22 17:51:18

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)

This query shows the data and sorts by large quantities.
There are 75,000 data in the database and it takes almost 5 minutes. How can I simplify this option so that it loads them faster

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Aksentiev, 2018-06-22
@Sanasol

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.

K
Koteezy, 2018-06-22
@Koteezy

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();

Something like this. In DB::raw change to your sql, I don't know what tables and keys you have.

Y
Yan-s, 2018-06-22
@Yan-s

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 question

Ask a Question

731 491 924 answers to any question