Laravel - Get records from one table that doesn't exist in another with a where clause attached
$current_academic = Academic::where('status', 1)->first();
$students = \DB::table('students')
->select(
'students.id',
'first_name'
)
->whereNotExists( function ($query) use ($current_academic) {
$query->select(DB::raw(1))
->from('enrollments')
->whereRaw('students.id = enrollments.student_id')
->where('enrollments.academic_id', '=', $current_academic->id);
})
->get();
Let's give some details:
1- whereNotExists
clause will return only students that doesn't have any row in the sub query.
2- the sub query select students that exists in enrollments table and their academics_id is 10
Hope this helps
$students = \DB::table('students')
->select(
'students.id',
'first_name'
)
->leftJoin('enrollments','enrollments.student_id','=','students.id')
->whereNull('enrollments.student_id')
->orWhere('enrollments.academic_id','<>',$current_academic->id)
->get();
Let's do this the most eloquential way possible:
First off, you need to have this in your Student.php model file
public function academics()
{
return $this->belongsToMany('App\Academic', 'enrollments', 'student_id', 'academic_id');
}
and this in your Academic.php model file
public function students()
{
return $this->belongsToMany('App\Student', 'enrollments', 'academic_id','student_id');
}
now you can get what you want this way:
$students = \App\Student::whereDoesntHave('academics')
->orWhereHas('academics',function($q) use ($academic){
$q->where('id',$academic->id)->count();
},'=',0)->get();