有没有办法从表中获取随机行并向所有用户显示同一行?我知道我可以使用 random() 方法来获取行,但如何向所有用户显示同一行。这是我的控制器:-<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use Illuminate\Database\Query\Builder::inRandomOrder;use App\Nothingness;class NothingnessController extends Controller{ public function randomQuestion() { $seed = Carbon::now()->toISOString(); Nothingness::inRandomOrder($seed)->first(); return view('home', compact('seed')); }}这是一个新的 Laravel 项目
1 回答
![?](http://img1.sycdn.imooc.com/545865620001c45402760276-100-100.jpg)
慕容森
TA贡献1853条经验 获得超18个赞
使用Illuminate\Database\Query\Builder::inRandomOrder
方法并为其提供种子。
该方法是通过 __call 魔术方法在 Eloquent 模型中实现的。
种子可确保同一种子的结果排序相同。
以下是一个查询,其中每个在同一分钟查看的人都会看到相同的记录。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use App\Nothingness;
class NothingnessController extends Controller
{
public function randomQuestion()
{
$seed = Carbon::now()->format('Y-m-d H:i');
$randomNothing = Nothingness::inRandomOrder($seed)->first();
return view('home', compact('randomNothing'));
}
}
您也可以从外部来源获得种子。
- 1 回答
- 0 关注
- 87 浏览
添加回答
举报
0/150
提交
取消