动态搜索——Laravel where Raw不起作用


Dynamic search -- Laravel whereRaw not working

我正在尝试根据搜索键在Individualprofile模型中搜索记录。从浏览器查看时,下面的路由引发Call to undefined method Illuminate'Database'Eloquent'Collection::whereRaw()异常。

在foreach循环中,我尝试了Individualprofile::whereRaw(..),但仍然存在相同的问题。

以下是我的完整路线实现。

Route::get('/get-individualprofiles',function(){
        $text = "Lamin";
        if(trim($text) == ""){
            return Individualprofile::take(10)->get();
        }
        $substr = preg_split("/['s,.()&;:_-]+/",preg_replace("/('w+)/","%$1%",trim($text)),-1,PREG_SPLIT_NO_EMPTY);
        $profiles = Individualprofile::all();
        foreach ($substr as $key) {
            $profiles = $profiles->whereRaw('(name like ? or mobile like ? or address like ? or occupation like ? or mstatus like ?)',[$key,$key,$key,$key,$key]);
        }
        return $profiles->take(100)->get();
    });

您正在尝试对Collection实例使用Query Builder方法。尝试使用这个:

$profiles = Individualprofile::query();
foreach ($substr as $key) {
    $profiles = $profiles->whereRaw('(name like ? or mobile like ? or address like ? or occupation like ? or mstatus like ?)',[$key,$key,$key,$key,$key]);
}
return $profiles->take(100)->get();

Individualprofile::all()返回get()的结果,这意味着您得到的是Collection,而不是具有whereRaw方法的Builder实例。query()方法将为您的模型返回一个Builder实例,您可以使用它来构建查询。