Laravel搜索逻辑问题

时间:2016-04-19 01:53:01

标签: laravel laravel-5.1

我正在Laravel 5.1中开发一个搜索模块,用于搜索商家及其电话号码(记录)。

-- TABLES
businesses: id, name, status
records: id, business_id, number, note

当找到给定关键字的商家名称和记录备注时,搜索必须返回结果。目前,即使相关记录(注释)不匹配,它也会返回所有业务。

以下是代码: -

$keywords = explode(" ", Request::get('keywords'));
$businesses = App\Business;

$businesses = $businesses->where(function ($query) use ($keywords) {
    foreach ($keywords as $name) {
        $query->orWhere('name', 'like', "$name%");
    }
});

$businesses = $businesses->with(['records' => function ($query) use ($keywords) {
    $query->where('note', 'like', '%'.$keywords[0].'%');

    foreach ($keywords as $note) {
        $query->orWhere('note', 'like', "%$note%");
    }
}]);

$businesses = $businesses->where('status', 1);
$businesses = $businesses->paginate($limit);

return $businesses;

1 个答案:

答案 0 :(得分:0)

不要爆炸关键字,因为它们按照提到的空格分隔。请尝试以下方法。

$businesses = $businesses->with(['records' => function ($query) use ($keywords) {
            $query->where('note', 'like', '%'.$keywords.'%');
        }])->where('name', 'like', '%'.$keywords.'%')->get();