#Database improve getting last x records

15 messages · Page 1 of 1 (latest)

white crystal
#

I have huge database model of around 1 million records, and on request I only want to get last 50 records from the database. Currently I do that by this

$models = Model::latest('id')->take(50)->get();

but when I look at debugbar, it shows 1 mil models were used, it also used a big amount of memory and rapidly slowed the request.
Is there any way of not storing whole database model into memory and just take those last records ?

jolly flare
#

Are you sure that's where it originates from? Afaik that would end up with a query like select * from models order by id DESC limit 50 so that wouldn't load all records.

left lantern
#

It's probably another line of code that loads all those rows/models

jolly flare
#

@white crystal feelswaitingman

white crystal
#

sorry I have been on dinner

#

and yeah, I found what si causing it

#
// changed this:
Model::latest()->pluck('id')->first()
// into this:
Model::latest()->first()->id
#

that was loading id of all records I guess and after that took the first one

left lantern
#

Yeah, you can do ->first('id')->id if you want to change that SELECT * to SELECT id

left lantern
#

That performs a SELECT id FROM ... WHERE ... and loads that specific model, yes.
If you then want the primitive id value, you do ->id

#

first() performs a SELECT *. If you only need the id column (like you wrote before), then first('id') is much more performant

white crystal
#

I understand

jolly flare
#

Great, so this is solved then? 🙂