is there a more elegant way to do what the code below does without use "foreach"? I am trying to load answers from questions but only the answers that contains a direct relation with an Appointment
public function show(Request $request, Patient $patient)
{
$user = $request->user();
$appointments = Appointment::with('forms.questions')
->where('patient_id', $patient->id)
->where('user_id', $user->id)
->get();
foreach ($appointments as $appointment) {
foreach ($appointment->forms as $form) {
foreach ($form->questions as $question) {
$question->load(['answers' => function ($q) use ($appointment) {
$q->where('appointment_id', $appointment->id);
}]);
}
}
}
return view('patients.show', compact('patient', 'appointments'));
}
I tried with no luck
public function show(Request $request, Patient $patient)
{
$user = $request->user();
$appointments = Appointment::with(['forms.questions.answers' => function ($query) {
$query->where('answers.appointment_id', 'appointments.id')
}])
->where('patient_id', $patient->id)
->where('user_id', $user->id)
->get();
return view('patients.show', compact('patient', 'appointments'));
}
EDIT: Below are the relationships
Form
- questions (hasMany)
- appointments (belongsToMany)
Question
- answers (hasMany)
Answer
- question (belongsTo)
- appointment (belongsTo)
Appointment
- answers (hasMany)
- forms (belongsToMany)
- patient (hasOne)
- user (hasOne)
Patient
- user (BelongsTo)
- appointments (hasMany)
User
- appointments (hasMany)
A table called appointment_form is a pivot table for appointments and forms table.
patient_id
to something different? \$\endgroup\$