a salamo alaikom try this my friend <<
// app/Models/Major.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Major extends Model { public function students() { return $this->hasMany(Student::class); }
public function subjects()
{
return $this->belongsToMany(Subject::class, 'subject_major');
}
}
// app/Models/Subject.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Subject extends Model { public function majors() { return $this->belongsToMany(Major::class, 'subject_major'); }
public function grades()
{
return $this->belongsToMany(Grade::class, 'questions');
}
}
// app/Models/Grade.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Grade extends Model { public function subjects() { return $this->belongsToMany(Subject::class, 'questions'); }
public function rooms()
{
return $this->hasMany(Room::class);
}
}
// app/Models/Student.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model { public function major() { return $this->belongsTo(Major::class); }
public function room()
{
return $this->belongsTo(Room::class);
}
}
// on the related controller do this
function getStudentsBySubjectAndGrade($subjectId, $gradeId) { $students = Student::whereHas('major.subjects', function ($query) use ($subjectId) { $query->where('subjects.id', $subjectId); })->whereHas('room.grade.subjects', function ($query) use ($subjectId, $gradeId) { $query->where('subjects.id', $subjectId)->where('grades.id', $gradeId); })->get();
return $students;
}
Thanks for your answer! Yes i got it. I am not good at in querying relationship. But i don't want to use DB. So, i read the documentation many times after that i see about the subquery in query. I got the solution with that way.
Thanks!
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.