[英]how to retrieve data from laravel relationship?
您好,我正在尝试使用 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 这样的关系来解决这个问题,但不会起作用。
那是我的 model:
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
编辑:我想我知道为什么我无法用我的关系检索数据..我在类别 Class 中的关系有错误,我没有 questions_id 字段,我将其替换为:
public function question()
{
return $this->hasMany(Question::class);
}
现在我可以得到以下问题:
public function startQuiz(Request $request){
$questions = Question::all();
$questionsCategory = [];
if($request){
foreach ($questions as $question) {
if ($request->categoryTest == $question->category->name) {
$questionsCategory = $question->where('categories_id', '=', $question->category->id)
->get();
var_dump($questionsCategory);
}
}
}
}
尝试用'='
替换'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(); }
对于您的表单列表,您可能已经有了$categories = Categories::all()
。 接下来要在提交后获得该类别的所有问题,您应该首先获得该类别,然后再获得该类别的问题。 假设您的表单中有类别 ID:
$categoryQuestions = Category::find($request->get('id'))->questions;
我看到您正在为您的 url 使用类别 slug,也可以使用它来查找类别:
public function startQuiz(Request $request, string $slug){
$questions = Category::whereSlug($slug)->first()->questions;
...
}
奖励:在您的服务提供商中,您可以将 {category} 直接绑定到您的 model ,如下所示:
Route::bind('category', function($value) {
return Category::whereSlug('slug', $value)->first();
});
然后您的类别将在 controller 方法中可用:
public function startQuiz(Request $request, Category $category){
$questions = $category->questions;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.