K
K
kaxa32012022-03-06 21:56:32
SQL
kaxa3201, 2022-03-06 21:56:32

How to speed up query with groupBy?

How can you speed up sampling? There are a lot of records

$rows->get()->groupBy(function ($item) {
                    return sprintf(
                        '%s by %s',
                        $item->created_at->format('Y-m-d H:i:s'),
                        is_null($item->user) ? 'undefined' : $item->user->getNameAttribute()
                    );
                }
            )->paginate($paginate);

The result of my selection
6225048dea540703950223.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Anton, 2022-03-07
@kaxa3201

If this is constantly needed, then you can denormalize: add a table model with a grouping value (return sprintf(
'%s by %s',
$item->created_at->format('Ymd H:i:s'),
is_null ($item->user) ? 'undefined' : $item->user->getNameAttribute()
); and that's all), and the field in the source table with its id, make an index by the grouping value, get only the necessary grouping values from this table, and then, after receiving the page, already get the necessary data of the source table there, for example, through https://laravel.com/docs/8.x/eloquent-relationship...

V
Vyacheslav Plisko, 2022-03-09
@AmdY

You are confusing a query to the database and working with a collection.
$rows->get() - has already returned a bunch of garbage to you, and then you work with it on the php side. Do grouping on the DB side using sql
$rows->groupBy(...)->get()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question