你好我正在尝试用 laravel 做一个测验应用程序并且我正在努力检索我的类别问题..我对此有一个难看的解决方案,但它不是动态的..public function startQuiz(Request $request){ $questions = Question::all(); foreach ($questions as $key => $question) { dd($question->where('categories_id', 'LIKE', 2)->get()); // i want to change the 2 to the real category id }}我以为我可以通过 $question->category->id 之类的关系来解决这个问题,但行不通。那是我的模型:class Question extends Model{ protected $fillable = ['question_text', 'categories_id', 'correct_answer', 'options']; protected $casts = ['options' => 'array']; public function category(){ return $this->belongsTo(Category::class, 'categories_id'); }}class Category extends Model{ protected $fillable = ['name', 'slug']; public function question() { return $this->hasMany(Question::class, 'questions_id'); }我不能以某种方式传递 id 并检查它我不知道为什么..那是我传递类别的表格:@section('content-categories')<div class="card"> <div class="card-header">Choose Category to Start</div> <div class="card-body"> @foreach($categories as $category) <form class="form-group" action="{{route('user.quiz', $category->slug)}}" method="post"> @csrf <input type="submit" name="categoryTest" class="form-control" value="{{$category->name}}"> </form> @endforeach </div></div>@endsection
2 回答
红糖糍粑
TA贡献1815条经验 获得超6个赞
对于您的表单列表,您可能已经拥有$categories = Categories::all()
. 接下来要在提交后获取该类别的所有问题,您应该首先获取类别,然后再针对它提出问题。假设您的表单中有类别 ID:
$categoryQuestions = Category::find($request->get('id'))->questions;
我看到您正在为您的网址使用类别 slug,也可以使用它来查找类别:
public function startQuiz(Request $request, string $slug){ $questions = Category::whereSlug($slug)->first()->questions; ... }
奖励:在您的服务提供商中,您可以像这样将 {category} 直接绑定到您的模型:
Route::bind('category', function($value) { return Category::whereSlug('slug', $value)->first(); });
然后你的类别将在控制器方法中可用:
public function startQuiz(Request $request, Category $category){ $questions = $category->questions; }
猛跑小猪
TA贡献1858条经验 获得超8个赞
尝试替换'LIKE'
为'='
. dd(...)
并像这样删除:
foreach ($questions as $key => $question) {
dd($question->where('categories_id', 'LIKE', 2)->get());
}
到:
foreach ($questions as $key => $question) {
$question->where('categories_id', '=', 2)->get();
}
- 2 回答
- 0 关注
- 120 浏览
添加回答
举报
0/150
提交
取消