Laravel中如何用Eloquent生成适配in_array的数组并检查数组数据
解决方案:生成
in_array可用数组 + Eloquent数组检查方法 一、生成可用于in_array的数组
你当前的代码其实已经生成了符合要求的数组!看这段:
$question_check = TestsResultsAnswer::where('user_id', auth::id())->pluck('question_id')->toArray();
pluck('question_id')会提取所有匹配用户的question_id字段,返回一个CollectiontoArray()把Collection转成标准PHP索引数组,直接就能传给in_array()使用
优化小技巧
如果数据库里可能存在重复的question_id记录(比如用户重复提交同一题),可以加->unique()去重,避免数组里有冗余数据:
$question_check = TestsResultsAnswer::where('user_id', auth()->id()) ->pluck('question_id') ->unique() // 去重 ->toArray();
二、Laravel Eloquent如何检查数组中的数据
Eloquent提供了whereIn和whereNotIn两个核心方法,直接在数据库层面完成数组匹配,比在PHP里用in_array()过滤更高效(尤其是数据量大的时候)。
常用场景示例
1. 排除用户已答过的题目(你的测验功能核心需求)
修改你获取题目代码,直接从数据库过滤掉已答的题,避免重复出题:
$questions = Chapter::find($id) ->questions() ->whereNotIn('id', $question_check) // 检查question.id不在已答数组里 ->inRandomOrder() ->limit(1) ->first();
2. 查询存在于数组中的记录
比如要批量查询多个ID的题目:
$target_ids = [1,3,5]; $selected_questions = Question::whereIn('id', $target_ids)->get();
3. 组合条件查询
可以和其他条件结合使用:
$active_questions = Question::where('status', 'active') ->whereIn('chapter_id', [2,4,6]) ->get();
视图中使用in_array的示例
如果需要在前端判断当前题目是否已答,直接用生成的数组即可:
@if($questions) <div class="question-card"> <h4>{{ $questions->content }}</h4> @if(in_array($questions->id, $question_check)) <span class="badge bg-secondary">已作答</span> @endif </div> @else <p>该章节所有题目你都已经完成啦!</p> @endif
内容的提问来源于stack exchange,提问作者Hassan
相关产品推荐
相关产品推荐

