Support the ongoing development of Laravel.io →
Laravel
0

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;

}

thetpainghtut liked this reply

1

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!

hoceinemuslim liked this reply

1

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.