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

你好我正在尝试用 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


犯罪嫌疑人X
浏览 121回答 2
2回答

红糖糍粑

对于您的表单列表,您可能已经拥有$categories = Categories::all().&nbsp;接下来要在提交后获取该类别的所有问题,您应该首先获取类别,然后再针对它提出问题。假设您的表单中有类别 ID:$categoryQuestions&nbsp;=&nbsp;Category::find($request->get('id'))->questions;我看到您正在为您的网址使用类别 slug,也可以使用它来查找类别:public&nbsp;function&nbsp;startQuiz(Request&nbsp;$request,&nbsp;string&nbsp;$slug){ &nbsp;&nbsp;&nbsp;$questions&nbsp;=&nbsp;Category::whereSlug($slug)->first()->questions; &nbsp;&nbsp;&nbsp;... }奖励:在您的服务提供商中,您可以像这样将 {category} 直接绑定到您的模型:Route::bind('category',&nbsp;function($value)&nbsp;{&nbsp; &nbsp;&nbsp;return&nbsp;Category::whereSlug('slug',&nbsp;$value)->first(); });然后你的类别将在控制器方法中可用:public&nbsp;function&nbsp;startQuiz(Request&nbsp;$request,&nbsp;Category&nbsp;$category){&nbsp; &nbsp;&nbsp;&nbsp;$questions&nbsp;=&nbsp;$category->questions; }

猛跑小猪

尝试替换'LIKE'为'='.&nbsp;dd(...)并像这样删除:foreach ($questions as $key => $question) { &nbsp; &nbsp;dd($question->where('categories_id', 'LIKE', 2)->get()); &nbsp;}到:foreach ($questions as $key => $question) { &nbsp; &nbsp;$question->where('categories_id', '=', 2)->get(); &nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP