动态搜索 - Laravel whereRaw不工作

fan*_*ndi 1 php laravel eloquent

我试图基于搜索键在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();
    });
Run Code Online (Sandbox Code Playgroud)

Bog*_*dan 5

您正在尝试将Query Builder方法与Collection实例一起使用.试试这个:

$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();
Run Code Online (Sandbox Code Playgroud)

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