【问题标题】:How to solve Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous in laravel如何解决完整性约束违规:1052 列 'id' in where 子句在 laravel 中不明确
【发布时间】:2019-11-23 16:40:47
【问题描述】:

我在学生和部门之间有 belongsToMany 关系。 现在我想获取部门的 subject_id 为空的所有学生部门。我在下面的代码,但它给了我以下错误

SQLSTATE[23000]:完整性约束违规:1052 where 子句中的列 'id' 不明确(SQL:select * from departments where subject_id 为空且存在(select * from students inner join @987654324 @ on students.id = department_student.student_id 其中departments.id = department_student.department_idid = 16 和 students@35 为空。 )

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

任何帮助将不胜感激

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您应该指定引用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();
    

    【讨论】:

    • 是的,它解决了问题,但我认为我将从关系中获得表名,这就是我没有使用它的原因
    猜你喜欢
    • 2020-10-13
    • 2020-11-23
    • 2013-10-16
    • 2019-04-14
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多