简体   繁体   English

如何从 laravel 关系中检索数据?

[英]how to retrieve data from laravel relationship?

Hello im trying to do a quiz app with laravel and im struggeling with retrieving my questions with category..您好,我正在尝试使用 laravel 做一个测验应用程序,并且我正在努力用类别检索我的问题..

i have a unsightly solution with this but it's not dynamically..我对此有一个难看的解决方案,但它不是动态的..

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 
  }
}

i thought i could to that with the relationship like $question->category->id but wont work.我想我可以通过 $question->category->id 这样的关系来解决这个问题,但不会起作用。

thats my model:那是我的 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');
    }

i cant somehow pass the id and check it i dont know why.. thats my form where i pass the category:我不能以某种方式传递 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

Edit: i think i know why i couldnt retrieve data with my relationship..i had an error with my relationship in Category Class, i have not a field for questions_id, i replaced it to:编辑:我想我知道为什么我无法用我的关系检索数据..我在类别 Class 中的关系有错误,我没有 questions_id 字段,我将其替换为:

    public function question()
    {
        return $this->hasMany(Question::class);
    } 

and now i could get the questions with:现在我可以得到以下问题:

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);
          }
        }
      }
    }

Try replacing 'LIKE' with '=' .尝试用'='替换'LIKE' ' 。 And remove dd(...) Like this:并删除dd(...)像这样:

foreach ($questions as $key => $question) { dd($question->where('categories_id', 'LIKE', 2)->get()); }

to:至:

foreach ($questions as $key => $question) { $question->where('categories_id', '=', 2)->get(); }

For your form listing probably you already have $categories = Categories::all() .对于您的表单列表,您可能已经有了$categories = Categories::all() Next to get all questions of this category after the submit you should first get the category and then questions for it.接下来要在提交后获得该类别的所有问题,您应该首先获得该类别,然后再获得该类别的问题。 Let say you have category id in your form:假设您的表单中有类别 ID:

$categoryQuestions = Category::find($request->get('id'))->questions;

I see you are using category slug for your url, can also use it to find the category:我看到您正在为您的 url 使用类别 slug,也可以使用它来查找类别:

public function startQuiz(Request $request, string $slug){
   $questions = Category::whereSlug($slug)->first()->questions;
   ...
}

Bonus: In your service provider you can bind {category} directly to your model like this:奖励:在您的服务提供商中,您可以将 {category} 直接绑定到您的 model ,如下所示:

Route::bind('category', function($value) {
   return Category::whereSlug('slug', $value)->first();
});

And then your category will be available in controller methods:然后您的类别将在 controller 方法中可用:

public function startQuiz(Request $request, Category $category){
    $questions = $category->questions;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM