Symfony\Component\Debug\Exception\FatalThrowableError 在 laravel 中调用 bool 的成员函数 get()?

Symfony\Component\Debug\Exception\FatalThrowableError Call to a member function get() on bool in laravel?

我想做一个用户名和班次模式id的搜索功能。按用户轮班模式 ID 搜索效果很好,但不适用于按名称搜索。有关详细信息,nameuser table 中,而 shift pattern id 是在 用户轮班模式 table.

UserShiftPattern 模型:-

    public function uspname(){
      return $this->belongsTo(User::class, 'user_id');
    }

UserShiftPatternController:-

public function index(Request $req)
{
    $usershiftpattern = [];

    if($req->filled('searching')){
        $usershiftpattern = $this->fetch($req);
    }

    return view('admin.usershiftpattern', ['usps' => $usershiftpattern]);
}

public function fetch(Request $req)
{
    $fname = explode(",", str_replace(' ','',$req->inputName));
    $fshiftpatternid = explode(",", str_replace(' ','',$req->inputShiftPatternId));

    $usershiftpatternlist = UserShiftPattern::query();
    $userusp = UserShiftPattern::with('uspname')->get();

    if(isset($req->inputName)){
        $usershiftpatternlist = $userusp->whereIn('name',$fname);
    }
    
    if(isset($req->inputShiftPatternId)){
        $usershiftpatternlist = $usershiftpatternlist->whereIn('shift_pattern_id',$fshiftpatternid);
    }

    $usershiftpatternlist = $usershiftpatternlist->has('uspattern')->get();

    return $usershiftpatternlist;
}    

视图:-

<tbody>
                @foreach($usps as $uspslists => $uspslist)
                <tr>
                    <td>{{ $uspslist->uspattern->name }}</td>
                    <td>{{ $uspslist->shift_pattern_id }}</td>
                </tr>
                @endforeach
            </tbody>

出现错误:-

Symfony\Component\Debug\Exception\FatalThrowableError Call to a member function get() on bool

请帮忙谢谢

我觉得你需要修改你的查询

    $fshiftpatternid = explode(",", str_replace(' ','',$req->inputShiftPatternId));
    
    $usershiftpatternlist = UserShiftPattern::query();
       
    
  if(isset($req->inputName)&&!empty($req->inputName)){
    $usershiftpatternlist = $usershiftpatternlist->whereHas('uspname',function($q)use($req){
     $q->where('name','like',  "%{$req->inputName}%");
    });
}
    
    if(isset($req->inputShiftPatternId)){
        $usershiftpatternlist = $usershiftpatternlist->whereIn('shift_pattern_id',$fshiftpatternid);
    }
    
    $usershiftpatternlist = $usershiftpatternlist->has('uspattern')->get();
    
    return $usershiftpatternlist;