Laravel:嵌套关系搜索

时间:2018-03-30 12:11:18

标签: php mysql database laravel-5 eloquent

我有两个嵌套关系,一个是requester.linkrequester.company,我希望两者都搜索单词$request->search

代码是自我解释的:

$clients = \App\AcceptedConnection::with('requester.link', 'requester.company')
    ->where('accepter_id', Auth::user()->id)
    ->orWhereHas('requester.link', function ($query) use ($request) {
        $query->orWhere('name', $request->search);
    })->orWhereHas('requester.company', function ($query) use ($request) {
        $query->orWhere('email', $request->search);
        $query->orWhere('firstname', $request->search);
        $query->orWhere('lastname', $request->search);
    })->get();

它为我提供了搜索到的任何内容的记录,即使搜索不匹配也会返回记录,搜索任何内容,它会为您提供记录,

我缺少什么?

1 个答案:

答案 0 :(得分:1)

您正在检查accepter_id=Auth::user()->id或记录是否与您的搜索字词匹配。

您必须将whereHas()个检查包装到闭包中:

$clients = \App\AcceptedConnection::with('requester.link', 'requester.company')
    ->where('accepter_id', Auth::user()->id)
    ->where(function($query) use ($request) {
        $query->whereHas('requester.link', function ($query) use ($request) {
            $query->orWhere('name', $request->search);
        })->orWhereHas('requester.company', function ($query) use ($request) {
            $query->orWhere('email', $request->search);
            $query->orWhere('firstname', $request->search);
            $query->orWhere('lastname', $request->search);
        });
    })->get()