php – 如何仅使用laravel中的where子句查询相关记录?

我尝试使用以下查询搜索属于特定用户/学校的学生.我已经创建了用户和学生之间的一对多关系..一切似乎都没问题,但是当我尝试搜索学生时,它也会给出我属于其他用户的学生列表.

public function searchStudent(Request $request)
{
    $q = $request->q;
    $grades = Auth::user()->grades;
    $searchPupils = Student::where('user_id','=',Auth::user()->id)->where('name','LIKE','%'.$q.'%')->orWhere('email','LIKE','%'.$q.'%')->get();

    if(count($searchPupils) > 0)
    {
        return view('add-class', compact('grades'))->withDetails($searchPupils)->withQuery($q);
    }
    else
    {
        return view ('add-class', compact('grades'))->withMessage('No Details found. Try to search again !');
    }
}

我也尝试过

$searchPupils = Auth::user()->students()->where('name','LIKE','%'.$q.'%')->orWhere('email','LIKE','%'.$q.'%')->get();

它仍在搜索整个学生表.应该怎么做?

最佳答案 >问题出在你的查询条件中,使用advance where子句如下所示.

$searchPupils =Student::where('user_id','=',Auth::user()->id)
            ->where(function($query)use($q){
                   $query->where('name','LIKE','%'.$q.'%')
                        ->orWhere('email','LIKE','%'.$q.'%');
              })->get();
点赞