在L-4中很简单:
$random_quote = Quotation::all()->random(1);
但是现在在L-5中,这篇文章中描述的单一方法没有工作: Laravel - Eloquent或Fluent随机行
我的视图文件只是空白.有任何想法吗?
编辑:
解决: $ random_quote = Quotation :: orderByRaw("RAND()") - > first();
Laravel 5.4的更新
Laravel 5.4中的新randomsorting
->inRandomOrder()->first()
orderByRaw('RAND()')有两个问题:
它取决于MySQL服务器
它在大型表上可能很慢(提取所有行)
这是我使用的解决方案,似乎更好一点:
$cnt = $records->count(); if ($cnt == 0) return; $randIndex = rand(0, $cnt-1); $obj = $records->skip($randIndex)->take(1)->first();
编辑:请注意,如果在"count()"和"skip()"之间删除某些记录,如果对数据库发出并行请求,我的解决方案可能会出现问题(如果没有运气则会崩溃).
更新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 - 快乐的编码!当你看到它时投票,所以它会在页面上升:)
random()
在5.2中给出错误,所以你可以使用inRandomOrder
https://laravel.com/docs/5.2/queries#ordering-grouping-limit-and-offset,
它适用于Eloquent之类的
Model::inRandomOrder()->first()
使用本杰明的想法,我会以不同的方式实现这一点.对此的查询范围感觉合适,因此它可以重复使用,并且它属于您正常的Eloquent使用.
注意: 在Eloquent 5.2中,内置了对全局范围的支持.
我将创建一个模型可以使用的特性,但您可以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; //... }
正在使用:
$randomQuote = \Quotation::random()->first();
这些工作,但可能你没有使用正确的namespace
,只需使用use
你的class
名字顶部的语句,如下所示:
<?php namespace SomeNamespace;
use App\Quotation; // Says "Quotation.php" is in "App" folder (By default in L-5.0)
class someClass {
//...
}
然后你可以使用这样的method
东西:
// 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();