动态搜索 - Laravel whereRaw不工作

时间:2014-11-11 17:58:04

标签: 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();
    });

1 个答案:

答案 0 :(得分: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();

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