how get random row laravel-5

前端 未结 9 656
花落未央
花落未央 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:23

    I'd implement this a little differently, using Benjamin's idea. A Query Scope for this feels appropriate so it's reusable, and it falls into your normal Eloquent use.

    Note: In Eloquent 5.2, there is built in support for global scopes.

    I'm going to create a trait that models can utilize, but you can just add the scopeRandom method directly to your specific model.

    /app/GlobalScopes.php

     0 ? mt_rand(0, $totalRows) : 0;
    
            return  $query->skip($skip)->take(1);
        }
    }
    

    Then, each model you want to utilize the global scopes, name the trait inside the class.

    /app/Quotation.php

    In use:

    $randomQuote = \Quotation::random()->first();
    

提交回复
热议问题