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

在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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据