douzuizhuo0587 2018-01-25 14:32 采纳率: 0%
浏览 1320
已采纳

在Laravel中的where,whereHas执行查询

I'm building a small application in Laravel 5.5 where I'm querying something like this:

$models = Contact::where('first_name', 'LIKE', '%'.$request->search_input.'%')
    ->orWhere('last_name', 'LIKE', '%'. $request->search_input.'%')
    ->orWhereHas('company', function ($q) use($request) {
        $q->where('name', 'LIKE', '%'.$request->search_input.'%');
    })
    ->whereHas('company', function ($query) {
        $query->where('type', '=', 'Research');
    })
    ->orderBy('created_at', 'desc')
    ->take(50)
    ->get();

The idea behind is, I want to search the list of contact with first_name, last_name and their company name (which is a relational data) with the search_input and filter them with type = Research in the company list, I mean only those contact should appear which is having company type as research.

But currently I'm getting all the list of contacts without filtering it with type. Help me out with this. Thanks.

  • 写回答

1条回答 默认 最新

  • duankang5882 2018-01-25 14:35
    关注

    You need to use where closure:

    Contact::where(function($q) use($request) {
            $q->where('first_name', 'like', '%' . $request->search_input . '%')
              ->orWhere('last_name', 'like', '%' . $request->search_input . '%')
              ->orWhereHas('company', function ($q) use($request) {
                  $q->where('name', 'like', '%' . $request->search_input . '%');
            });
        })
        ->whereHas('company', function ($query) {
            $query->where('type', 'Research');
        })
        ->latest()
        ->take(50)
        ->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?