简体   繁体   中英

Laravel Eloquent is performing query as an OR clause rather than AND which is intended

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

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 ...
if(!empty($names)) {
    $query->whereRaw('firstname LIKE "%{$names}%" OR lastname LIKE "%{$names}%" ');
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM