在 L-4 中,这很简单:
$random_quote = Quotation::all()->random(1);
但现在在 L-5 中,这篇文章中描述的方法没有一个有效:Laravel - Eloquent 或 Fluent 随机行 https://stackoverflow.com/questions/13917558/laravel-eloquent-or-fluent-random-row
我的视图文件变得空白。
这些有效,但可能你没有使用正确的方法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();
Or this:
$random_quote = Quotation::orderByRaw("RAND()")->first();
更新(自 Laravel - 5.2 起):
$random_quote = Quotation::inRandomOrder()->first();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)