Take 10 random strings from the top 100

Using Laravel Eloquent, how can I take 10 random rows from the top 100 (sorted by date).

For example, I have this:

$comments = Comment::orderBy('created_at', 'DESC')
    ->take(100)
    ->inRandomOrder()
    ->get();

How can I change this so that it takes 10 random lines from the 100 selected? Is there a way to do this, so that I do not need to extract 100 rows?

+4
source share
2 answers

1 is inRandomOrder()really slow, so I would not recommend using it.

2 - take(100)->random() 100 10 . , , 5 , :

$comments = Comment::latest()->take(100)->get();
$count = $comments->count() > 9 ? 10 : $comments->count();
$random =  $comments->random($count);

3 - , sort . 1 100 sort . 100 , - 0.

10 Radnom :

$comments = Comment::orderBy('sort')->take(10)->get();

, .

+2

random():

  $comments = Comment::orderBy('created_at', 'DESC')
        ->take(100)
        ->get()
        ->random(10);
0

Source: https://habr.com/ru/post/1661779/


All Articles