farshidpg
farshidpg

Reputation: 57

laravel select 5 random rows from the 20 most recent rows ( without mapping after load & do with one query )

how I can do this

Ex: select 5 random rows from the 20 most recent row

I need to do this with eloquent and get data with a query from DB not with mapping data

I found this query but I can't convert this to laravel eloquent …

Query :

select tbl1.* from (select *from DemoTable ORDER BY ShippingDate DESC LIMIT 20 ) as tbl1 -> ORDER BY RAND() LIMIT 5;

Upvotes: 0

Views: 1916

Answers (1)

Kongulov
Kongulov

Reputation: 1161

you can use this code. Change Models and columns for your models and columns. I wrote a user for the test

return User::query()
->whereIn('id', function($query)
{
   $query->from('users')
    ->selectRaw('id')
    ->orderByDesc('created_at')->limit(20);
})->inRandomOrder()->limit(5)->get();

if you get toSql() you see

select * from `users` where `id` in (select id from `users` order by `created_at` desc limit 20) limit 5

Upvotes: 0

Related Questions