Tanvir Ahmed
Tanvir Ahmed

Reputation: 1019

How to solve Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous in laravel

I have a belongsToMany relationship between the students and departments. Now i want to fetch all the departments of students where subject_id of departments is null. I below code but it gives me the following error

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from departments where subject_id is null and exists (select * from students inner join department_student on students.id = department_student.student_id where departments.id = department_student.department_id and id = 16 and students.deleted_at is null))

$departments=Department::where('subject_id','=',null)
                        ->whereHas('students',function($student){
                            $student->where('id',Auth::id());
                        })
                        ->get();
dd($departments);

Any help will be appreciated

Upvotes: 2

Views: 8397

Answers (1)

ascsoftw
ascsoftw

Reputation: 3476

You should specify the table name where you are referencing the id to avoid the ambiguity.

$departments=Department::where('subject_id','=',null)
->whereHas('students',function($student){ 
      $student->where('student.id',Auth::id()); //Notice the student.id instead of id
  })->get();

Upvotes: 6

Related Questions