php 我们有多个标题,但我如何才能在数组laravel中得到它

8fsztsew  于 2023-01-04  发布在  PHP
关注(0)|答案(1)|浏览(99)

我们必须找到与问题id相关的测验标题,但有多个测验具有相同的问题id.我们得到的回报是一个测验标题而不是全部.我能做什么?

$questions = DB::table('questionbank')
               
        ->leftJoin('questionbank_quizzes', function($join)
     {
         $join->on('questionbank_quizzes.questionbank_id','=','questionbank.id');
              
     })
     ->leftJoin('quizzes', function($join)
     {
         $join->on('quizzes.id','=','questionbank_quizzes.quize_id');
              
     })
       
        ->where('questionbank.subject_id', '=', $request->subject_id)
        ->get(['questionbank.id', 'questionbank.subject_id', 'topic_id', 'question_type', 'question', 'questionbank.marks', 'difficulty_level', 'status','quizzes.title']);

我尝试使用whereIn,但出现错误
为foreach()提供的参数无效

wh6knrhe

wh6knrhe1#

首先,您应该在模型之间创建一个relationship
问题库模型:

public function quizzes()
 {
    return $this->belongsToMany(Quiz::class);
 }

测验模型:

public function questions()
 {
    return $this->belongsToMany(QuestionBank::class);
 }

现在你可以使用eloquent类进行查询了:

$questions = QuestionBank::with('quizzes')
    ->where('subject_id', $request->subject_id)
    ->get()

foreach ($questions as $question) {
    // you have access to $question->quizzes as collection
}

相关问题