首页 文章

怎么得到随机行laravel-5

提问于
浏览
29

在L-4中很简单:

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

但是现在在L-5中,这篇文章中描述的单一方法没有工作:Laravel - Eloquent or Fluent random row

我的视图文件只是空白 . 有任何想法吗?

编辑:

Solved: $ random_quote = Quotation :: orderByRaw("RAND()") - > first();

9 回答

  • 8

    这些工作,但可能你没有使用正确的 namespace ,只需使用 class 名称顶部的 use 语句,如下所示:

    <?php namespace SomeNamespace;
    
    use App\Quotation; // Says "Quotation.php" is in "App" folder (By default in L-5.0)
    
    class someClass {
        //...
    }
    

    然后你可以在你的_1761945中使用这样的东西:

    // You may add: use DB; at the top to use DB instead of \DB
    $random_quote = Quotation::orderBy(\DB::raw('RAND()'))->first();
    

    或这个:

    $random_quote = Quotation::orderByRaw("RAND()")->first();
    

    更新(自Laravel-5.2):

    $random_quote = Quotation::inRandomOrder()->first();
    
  • 25

    random() 在5.2中给出错误,所以相反你可以使用 inRandomOrder https://laravel.com/docs/5.2/queries#ordering-grouping-limit-and-offset

    它适用于Eloquent之类的

    Model::inRandomOrder()->first()
    
  • 3

    Laravel 5.4的更新

    New randomsorting in Laravel 5.4 ->inRandomOrder()->first()

  • 13

    orderByRaw('RAND()')有两个问题:

    • 它依赖于MySQL服务器

    • 大型表格可能很慢(提取所有行)

    这是我使用的解决方案,似乎更好一点:

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

    编辑:请注意,如果在“count()”和“skip()”之间删除某些记录,如果对数据库发出并行请求,我的解决方案可能会出现问题(如果没有运气则会崩溃) .

  • 1

    更新LARAVEL 5.3

    我很高兴发现这是一个原生查询功能! :d

    inRandomOrder 方法可用于随机对查询结果进行排序 . 例如,您可以使用此方法来获取随机用户:

    $randomUser = DB::table('users')
                ->inRandomOrder()
                ->first();
    

    不幸的是,这些答案都没有充分利用Laravel 5的系列 . 如果您来自谷歌,像我一样,寻找完全原生的解决方案,请看下面!

    来自Alpha的答案具有数据库依赖性缺陷,正如他所指出的那样,本杰明在中间删除行时可能会出现问题 . 极不可能,但仍有可能 .

    这是一个在Laravel 5中选择随机行的单行解决方案

    // The setup
    $numberOfRows = 4;
    $models = Model::all(); // or use a ::where()->get();
    
    // And the actual randomisation line
    $randRows = $models->shuffle()->slice(0,numberOfRows);
    

    Et voila - 快乐的编码!当你看到它时投票,所以它会在页面上升:)

  • 11

    我使用Benjamin's idea以不同的方式实现这一点 . Query Scope对于这种感觉是合适的,所以它是可重复使用的,并且它属于您正常的雄辩使用 .

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

    我将创建一个模型可以使用的特性,但您可以直接将 scopeRandom 方法添加到您的特定模型中 .

    /app/GlobalScopes.php

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    trait GlobalScopes
    {
        public function scopeRandom($query){
            $totalRows = static::count() - 1;
            $skip = $totalRows > 0 ? mt_rand(0, $totalRows) : 0;
    
            return  $query->skip($skip)->take(1);
        }
    }
    

    然后,要使用全局范围的每个模型,在类中命名特征 .

    /app/Quotation.php

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Quotation extends Model
    {
        use GlobalScopes;
    
        //...
    }
    

    In use:

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

    在Laravel 5.1(和Laravel 5.2)中,Eloquent构建器返回的 Collection 类中有一个 random 方法 .

    https://laravel.com/docs/5.1/collections#available-methods

    所以你的电话

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

    要么

    $random_quote = Quotation::where('column', 'value')->get()->random(1);
    

    应该正常工作 .

  • 37
    orderByRaw('RAND()')
    

    注意:它会占用查询其余部分的所有行,所以如果你有一个大表,而不是同一个查询中的其他过滤器,它会给出糟糕的表现,否则这是你的选择

  • 12

    Laravel 5.4

    1)如果需要一个随机模型:

    $object = Model::all()->random();
    

    2)如果需要很多随机模型:

    $object = Model::all()->random($n); //$n - number of elements
                                        //$object - collection
    

    注释:调用$ collection-> random(1)现在将返回一个带有一个item的新集合实例 . 如果没有提供参数,此方法将只返回一个对象 .

    文件编号:https://laravel.com/docs/5.4/collections#method-random

相关问题