I am working on a site which includes a number of quizzes. A user can preform a quiz which is saved to an assessment. I have the following models:
class User
{
public function assessments()
{
return $this->hasMany(Assessment::class);
}
}
class Quiz
{
public function assessments()
{
return $this->hasMany(Assessment::class);
}
}
class Assessment
{
public function user()
{
return $this->belongsTo(User::class);
}
public function quiz()
{
return $this->belongsTo(Quiz::class);
}
}
To get a list of all the current authenticated user's assessments I am currently doing the following:
$quiz = Quiz::where('name', 'my quiz')->firstOrFail();
$assessments = Auth::user()->assessments()->where('quiz_id', $quiz->id)->get();
I am then passing both the quiz and the assessments to the view.
return view('quiz')->with('quiz', $quiz)->with('assessments', $assessments);
I'd like to know if there is a better way of doing this to reduce it to one sql query and also eager load the quiz into the results. Something like:
$assessments = Auth::user()->assessments()->with('quiz')->where('name', 'my quiz')->get();
Any thoughts?