Home > other >  Laravel query order the inrandormorder query
Laravel query order the inrandormorder query

Time:04-15

I have 40 rows in my table, what i want is to get 20 row randomly, and after order these 5 list by id; these 2 in one query;

for example in range of id 1 to 40; i get from the random order 15 10 14 9 3;so in the final result i expect to get 3 9 10 14 15

i tried to use inRandomOrder and orderBy in same time

$query->inRandomOrder()->orderBy('id', 'asc')

but the inRandomOrder query always has the final execution of my query; and if i switch their position:

$query->orderBy('id', 'asc')->inRandomOrder()

the orderBy always has the final execution

CodePudding user response:

2 solutions I guess, if you manipulate only dozens of rows, you can use Laravel collection to order by ID your query result.

Just use:

$result = $query->inRandomOrder()->get();

$resultSortedById = $result->sortBy('id');

Or using SQL query, you can use this query:

SELECT * FROM
(
    SELECT * FROM table
    ORDER BY RAND()
    LIMIT 20
) result
ORDER BY id ASC

You can translate in Eloquent way, or as SQL directly.

I am not sure to understand your question btw: order these 5 list by id ? What do you mean exactly ?

  • Related