how get random row laravel-5

前端 未结 9 665
花落未央
花落未央 2021-02-02 07:12

In L-4 it was simple:

$random_quote = Quotation::all()->random(1);

But now in L-5 not a single method described in this post is working: Lar

9条回答
  •  野的像风
    2021-02-02 07:17

    The orderByRaw('RAND()') has 2 issues:

    1. It's MySQL-server dependant
    2. It can be slow on large tables (fetches all rows)

    Here is the solution i used, which seems to be a bit better:

    $cnt = $records->count();
    if ($cnt == 0)
        return;
    
    $randIndex = rand(0, $cnt-1);
    $obj = $records->skip($randIndex)->take(1)->first();
    

    EDIT: Please note that my solution may be a problem (crash if no luck) in case of parrallel requests to the database, if some records are deleted between the "count()" and the "skip()".

提交回复
热议问题