获取唯一随机行Laravel Eloquent

wgeznvg7  于 2023-03-04  发布在  其他
关注(0)|答案(1)|浏览(136)

我正在处理一个多页的调查问卷,回答并进入下一页,我想从我的数据库中获取另一行尚未显示。
生成一个随机数后,我把这个值存储到一个数组中,这个数组在会话中,下次我查找随机行时,我检索这个数组来搜索 * 除了 * 存储在数组中的这些值
我将分享我的代码并解释:

$x = $this->generateRandInt($request); // random number stored in $x

$this->qs = $request->session()->get('arrayOfQs'); // get the session 

$question = Ctest::find($x['randomInt']); // here I'm simply looking for any random question

// This is the kind of approach I'm lookig for
// $question = Ctest::find($x['randomInt'])->whereNotIn('id', [$this->qs])->get();
// But I get error: Nested arrays may not be passed to whereIn method.

if ($this->qs) {
    array_push($this->qs, $x['randomInt']); // I store the used random into array
    $request->session()->put('arrayOfQs', $this->qs); // I store array into session
    var_dump($this->qs); // array(3) { [0]=> int(1) [1]=> int(3) [2]=> int(8) } 
}else{ // same actions but for the first iteration 
    $qs=[];
    array_push($qs, $x['randomInt']);
    $request->session()->put('arrayOfQs', $qs);
    var_dump($qs); array(3) { [0]=> int(1) } 
}

// This is my function to simply generate a random within a range
public function generateRandInt(Request $request)
{
    $randomInt = mt_rand(1, 20);
    return compact('randomInt');
}

使用Eloquent解决此问题的最佳方案是什么?
文档规定whereNotIn('field','array')应该可以工作,但我一定是漏掉了什么...
为什么不管用?

$question = Ctest::find($x['randomInt'])->whereNotIn('id', [$this->qs])->get();
4nkexdtk

4nkexdtk1#

可能是这样的你可以试试

$alreadySelected = []
$currentSelected = Ctest::whereNotIn('id', [alreadySelected])->inRandomOrder()->get();
$alreadySelected = array_merge($alreadySelected, $currentSelected->pluk(id)->toArray());

相关问题