简体   繁体   中英

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

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();

We also can use like this

->whereHas('students',function($student){ 
      $student->where('student.id', '=', Auth::id()); //Like this
  })->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM