[英]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.我在学生和部门之间有一个belongsToMany关系。 Now i want to fetch all the departments of students where subject_id of departments is null .
现在我想获取部门的 subject_id 为 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
wheresubject_id
is null and exists (select * fromstudents
inner joindepartment_student
onstudents
.id
=department_student
.student_id
wheredepartments
.id
=department_student
.department_id
andid
= 16 andstudents
.deleted_at
is null))SQLSTATE [23000]:完整性约束违规:1052 where 子句中的列 '
id
' 不明确(SQL:从subject_id
为空且存在的departments
中选择 *(从students
内部连接department_student
的students
中选择 *。id =department_student
student_id
wheredepartments
)id
=department_student
department_id
和id
= 16 和students
deleted_at
为空))
$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.您应该指定引用
id
的表名以避免歧义。
$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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.