dougan6982 2014-07-21 11:27
浏览 204
已采纳

Laravel Eloquent正在执行查询作为OR子句而不是AND

I am trying to build a query in Laravel 4 using the Eloquent ORM that simply matches all fields in the criteria. I have the below code which at present returns data that matches ANY of the criteria rather than ALL of the criteria, OR instead of AND if you will.

    $names = Input::get('names');
    $company = Input::get('company');

    $contacts = Contact::where(function($query) use ($names, $tags, $type, $sector, $company)
    {
        if (!empty($names)) {
            $query->where('firstname', 'LIKE', "%{$names}%")
            ->orWhere('lastname', 'LIKE', "%{$names}%");
        }
        if (!empty($company)) {
            $query->where('company', 'LIKE', "%{$company}%");
        }
    })
    ->paginate(100);


    return View::make('index')->with('contacts', $contacts)->with('searchingFlag', $searchingFlag)->with('names', $names)->with('tags', $tags)->with('type', $type)->with('sector', $sector)->with('company', $company);

So all I am doing here, I believe, is stating results must match either of the name fields AND the company field, if either is set, but as mentioned results are returned that match either of the clauses rather than both.

Can anyone help me figure out what's wrong?

Thanks

  • 写回答

2条回答 默认 最新

  • douti6740 2014-07-21 11:32
    关注

    You need to nest wheres:

    if (!empty($names)) {
        $query->where(function ($q) use ($names) {
          $q->where('firstname', 'LIKE', "%{$names}%")
           ->orWhere('lastname', 'LIKE', "%{$names}%");
        }
    }
    

    This will result in:

    SELECT ... WHERE (firstname like .. OR lasname like ..) AND company ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器