我的数据库查询从数据库返回随机行。当页面加载并在用户刷新页面时返回此随机字符串而不更改字符串时,有什么办法吗?
这是我的 Controller
public function view() {
$view = View::orderByRaw("RAND()")->limit('1')->get();
return View::make('site.view', [
'view' => $view
]);
}
我的 Blade 里有
@foreach($view as $rand)
{{ Form::open() }}
{{ $rand['my_view'] }}
// bunch of form fealds
<button type="submit" class="btn btn-primary">Submit</button>
{{ Form::clode() }}
@endforeach
所以这里用户得到了随机字符串,需要填写表单并添加该字符串。然后我将所有信息保存在数据库中。一切都完美保存在数据库中。问题是用户可以在提交表单后刷新多个时间表,并且当他看到另一个随机字符串时可能会感到困惑......
最佳答案
选项 #1 - 将从 :View::make
获取的数据保存到 session 中并返回
public function view() {
$rand_view = Session::get('rand_view');
if (!$rand_view) {
$view = View::orderByRaw("RAND()")->limit('1')->get();
$rand_view = View::make('site.view', [
'view' => $view
]);
Session::put('rand_view', $rand_view);
}
return $rand_view;
}
选项 #2 - 对于特定用户 - 始终生成相同的“随机数”:
public function view() {
// To make sure we generate the same RAND() we generate a random seed for each user and we save that seed in the session for that user.
$rand_seed = Session::get('rand_seed');
if (!$rand_seed) {
$rand_seed = mt_rand();
Session::put('rand_seed', $rand_seed);
};
$view = View::orderByRaw("RAND({$rand_seed})")->limit('1')->get();
return View::make('site.view', [
'view' => $view
]);
}
更新
经过一些调试后,选项 #1 似乎不起作用,因为 View::make
返回一个无法序列化的对象。如果您需要此解决方案,请使用选项#2
关于php - 来自数据库列的随机值,但在 Laravel 中仅出现一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39871290/