php - 来自数据库列的随机值,但在 Laravel 中仅出现一次

标签 php mysql laravel-4

我的数据库查询从数据库返回随机行。当页面加载并在用户刷新页面时返回此随机字符串而不更改字符串时,有什么办法吗?

这是我的 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/

相关文章:

mysql - 我的函数没有返回任何内容

MySQL 查询未按预期运行

php - 在 View 中循环验证错误

php - 在 mysql 中使用加密存储的密码进行摘要式身份验证

php - 如何从 MySQL 列中提取数据并将其放入单个数组中

php Spreadsheet_Excel_Reader 数据插入 mysql 数据库时包含不需要的 �

php - Laravel 使用 Eloquent 插入数据有两个有很多关系

php - 如何在 MySQL 中获取带有帖子 id 的帖子页面

php - MySql Password_verify() 不工作?

php - 获取不带扩展名的文件名