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

在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.

图片转代码服务由CSDN问答提供 功能建议

我正在 Laravel 5.5中构建一个小应用程序我在那里查询类似的东西 这个:

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

背后的想法是,我想用 first_name last_name 和他们的公司名称(这是一个关系数据)与 search_input 并用 type = Research 公司列表中,我的意思是只有那些 conta ct 应该出现 company type as research

但是目前我 获取所有联系人列表而不用类型过滤它。 帮助我解决这个问题。 谢谢。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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();
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题