【问题标题】:Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown columnIlluminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
【发布时间】:2021-04-15 15:20:04
【问题描述】:

我已尝试使用此代码返回所有学生及其在学校的信息。

$school=School::where('admin_id',auth()->user()->id)->first();
        return $user=User::with(["studentDetails"=>function($q) use($school){
            $q->where('studentDetails.school_id','=',$school->id);
        },"subscriptionsSatus.courses"])->get();

这是我的错误

Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'studentDetails.school_id' in 'where clause' (SQL: select * from `student_details` where `student_details`.`student_id` in (79, 81, 82, 83, 84, 85, 86, 87, 89, 90) and `studentDetails`.`school_id` = 7) in file

我在这里做错了什么......列名与数据库相同

【问题讨论】:

  • 在这里删除 studentDetails $q->where('studentDetails.school_id','=',$school->id); $q->where('school_id','=',$school->id);应该没问题
  • @skorp 好的,它可以工作,但它会将所有用户作为 studentdetails 返回为 null。我怎样才能避免这种情况我只需要返回具有 school_id =我的价值的用户

标签: laravel eloquent


【解决方案1】:

您不必指定列:

$school=School::where('admin_id',auth()->user()->id)->first();
        
return $user=User::with(["studentDetails"=>function($q) use($school){
            $q->where('school_id','=',$school->id);
        },"subscriptionsSatus.courses"])->get();


如果您只想返回拥有这所学校的用户,那么:

$school=School::where('admin_id',auth()->user()->id)->first();
        
return $user=User::with(["studentDetails"=>function($q) use($school){
            $q->where('school_id','=',$school->id);
        },"subscriptionsSatus.courses"])
->whereHas('studentDetails', function($query){
 $query->where('school_id','=',$school->id);
})->get();


【讨论】:

    猜你喜欢
    • 2019-06-06
    • 1970-01-01
    • 2020-12-01
    • 2018-02-04
    • 1970-01-01
    • 2016-07-22
    • 2018-09-10
    • 2011-03-16
    • 1970-01-01
    相关资源
    最近更新 更多